var treeMixin = {
    data: {
        readonly: true,
        dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
        total: 0,
        currentPageIndex: 1,
        lastTableHeight: 100,
        posiDetailHeight: 100,
        placeholder: "",
        sosoValue: '',
        isShowMatchDev: false,
        treeData: [],
        dayNumberType: 0,
        selectedCount: 0,
    },
    methods: {
        onClickIcon: function() {
            this.cleanSelectedDev();
            this.selectedCount = 0;
            this.sosoValue = '';
            this.checkedDevice = [];
        },
        clean: function() {
            this.selectedCount = 0;
            this.sosoValue = '';
            this.checkedDevice = [];
            this.treeDeviceList[0].open = true;
            this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, this.treeDeviceList);
            if (this.tableData) {
                this.tableData = [];
            }
        },
        cleanSelected: function(treeDataFilter) {
            var that = this;
            for (var i = 0; i < treeDataFilter.length; i++) {
                var item = treeDataFilter[i];
                if (item != null) {
                    item.checked = false;
                    if (item.children && item.children.length > 0) {
                        that.cleanSelected(item.children);
                    }
                }
            }
        },
        cleanSelectedDev: function() {
            this.clean();
        },
        changePage: function(index) {
            var offset = index * 20;
            var start = (index - 1) * 20;
            this.currentPageIndex = index;
            this.tableData = this.cmdRecords.slice(start, offset);
        },
        onClickOutside: function(e) {
            this.readonly = false;
            this.isShowMatchDev = false;
        },
        onChange: function(value) {
            this.dateVal = value;
        },
        handleSelectdDate: function(dayNumber) {
            this.dayNumberType = dayNumber;
            var dayTime = 24 * 60 * 60 * 1000;
            if (this.$el.id == 'acc-details') {
                if (dayNumber == 0) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now(), timeDifference) + ' 00:00:00', DateFormat.longToDateStr(Date.now(), timeDifference) + ' 23:59:59'];
                } else if (dayNumber == 1) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime, timeDifference) + ' 00:00:00', DateFormat.longToDateStr(Date.now() - dayTime, timeDifference) + ' 23:59:59'];
                } else if (dayNumber == 3) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 2, timeDifference) + ' 00:00:00', DateFormat.longToDateStr(Date.now(), timeDifference) + ' 23:59:59'];
                } else if (dayNumber == 7) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 6, timeDifference) + ' 00:00:00', DateFormat.longToDateStr(Date.now(), timeDifference) + ' 23:59:59'];
                }
            } else {
                if (dayNumber == 0) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
                } else if (dayNumber == 1) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime, timeDifference), DateFormat.longToDateStr(Date.now() - dayTime, timeDifference)];
                } else if (dayNumber == 3) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 2, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
                } else if (dayNumber == 7) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 6, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
                }
            }

        },
        focus: function() {
            this.readonly = false;
            this.isShowMatchDev = true;
        },
        sosoValueChange: function() {
            this.filterMethod(this.sosoValue.toLowerCase());
        },
        filterMethod: function(value) {
            if (value === '') {
                this.treeDeviceList[0].open = true;
                this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, this.treeDeviceList);
            } else {
                var data = this.variableDeepSearch(this.treeDeviceList, value, 0);
                if (data.length == 0) {
                    data.push({
                        name: isZh ? '无数据' : 'No data',
                        nocheck: true
                    })
                }
                this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, data);
            }

            this.checkedDevice = [];
            if (this.isShowMatchDev == false) {
                this.isShowMatchDev = true;
            }
        },
        variableDeepSearch: function(treeDataFilter, searchWord, limitcount) {
            var childTemp = [];
            var that = this;
            for (var i = 0; i < treeDataFilter.length; i++) {
                var copyItem = null;
                var item = treeDataFilter[i];
                if (item != null) {

                    var isFound = false;
                    if (item.name.toLowerCase().indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                        copyItem = item;
                        copyItem.open = false;
                        isFound = true;
                    }
                    if (isFound == false && item.children && item.children.length > 0) {
                        // item.expand = true;
                        // childTemp.push(item);
                        var rs = that.variableDeepSearch(item.children, searchWord, limitcount);
                        if (rs && rs.length > 0) {
                            copyItem = deepClone(item);
                            copyItem.children = rs;
                            copyItem.open = true;
                            isFound = true;
                        }
                    }

                    if (isFound == true) {
                        limitcount++;
                        childTemp.push(copyItem);

                        if (limitcount > 1000) {
                            break;
                        }
                    }
                }
            }
            return childTemp;
        },
        sosoSelect: function(item) {
            reportDeviceId = item.deviceid;
            this.sosoValue = item.allDeviceIdTitle;
            this.queryDeviceId = item.deviceid;
            this.isShowMatchDev = false;
        },
        getDeviceTitle: function(deviceid) {
            var title = "";
            this.groupslist.forEach(function(group) {
                var isReturn = false;
                group.devices.forEach(function(device) {
                    if (device.deviceid === deviceid) {
                        isReturn = true;
                        title = device.title;
                        return false;
                    }
                });
                if (isReturn) { return false };
            });
            return title;
        },
        onCheckedDevice: function(arr) {

            this.checkedDevice = arr;
            var sosoValue = "";
            var selectedCount = 0;
            arr.forEach(function(item) {
                if (item.deviceid != null) {
                    sosoValue += item.name + ","
                    selectedCount++;
                }
            });
            this.sosoValue = sosoValue;
            this.selectedCount = selectedCount;
            var allNodes = this.zTreeObj.getNodes();
            GlobalOrgan.getInstance().globalSelectedTreeData = null;
            GlobalOrgan.getInstance().globalSelectedTreeData = deepClone(allNodes);
        },
        initZTree: function(rootuser) {
            var me = this;
            this.treeDeviceList = [utils.castUsersTreeToDevicesTree(rootuser, true, false)];
            if (GlobalOrgan.getInstance().globalSelectedTreeData == null) {
                GlobalOrgan.getInstance().globalSelectedTreeData = this.treeDeviceList;
            }
            this.setting = {
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: {
                        "Y": "ps",
                        "N": "ps"
                    }
                },
                callback: {
                    onCheck: function(id, ztree) {
                        var checkedNodes = me.zTreeObj.getCheckedNodes();
                        me.onCheckedDevice(checkedNodes);
                    }
                }
            };
            this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, GlobalOrgan.getInstance().globalSelectedTreeData);
            this.selectedLastActiveDevice();

        },
        selectedLastActiveDevice: function() {
            var selectedDevices = this.zTreeObj.getCheckedNodes();
            if (selectedDevices.length > 0) {
                var sosoValue = '';
                var selectedCount = 0;
                selectedDevices.forEach(function(item) {
                    if (item.deviceid != null) {
                        sosoValue += item.name + ","
                        selectedCount++;
                    }
                });
                this.sosoValue = sosoValue;
                this.selectedCount = selectedCount;
                this.checkedDevice = selectedDevices;
            }
        },
    },
    mounted: function() {
        var me = this;
        try {
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        } catch (error) {}
    },
    watch: {
        currentPageIndex: function() {
            document.body.click();
        }
    },
    destroyed: function() {
        this.zTreeObj && this.zTreeObj.destroy();
    },
    created: function() {
        this.checkedDevice = [];
    },
};

var reportMixin = {
    data: {
        readonly: true,
        dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
        total: 0,
        currentPageIndex: 1,
        lastTableHeight: 100,
        posiDetailHeight: 100,
        placeholder: "",
        sosoValue: '',
        isShowMatchDev: true,
        filterData: [],
        queryDeviceId: '',
        dayNumberType: 0,
    },
    methods: {
        sosoSelectGroup: function(groupName) {
            this.filterMethod(groupName);
        },
        changePage: function(index) {
            var offset = index * 20;
            var start = (index - 1) * 20;
            this.currentPageIndex = index;
            this.tableData = this.cmdRecords.slice(start, offset);
        },
        onClickOutside: function() {
            this.readonly = true;
            this.isShowMatchDev = false;
        },
        onChange: function(value) {
            this.dateVal = value;
        },
        handleSelectdDate: function(dayNumber) {
            this.dayNumberType = dayNumber;
            var dayTime = 24 * 60 * 60 * 1000;
            if (dayNumber == 0) {
                this.dateVal = [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
            } else if (dayNumber == 1) {
                this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime, timeDifference), DateFormat.longToDateStr(Date.now() - dayTime, timeDifference)];
            } else if (dayNumber == 3) {
                this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 2, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
            } else if (dayNumber == 7) {
                this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 6, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
            } else if (dayNumber == 10) {
                this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 10, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
            } else if (dayNumber == 30) {
                this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 30, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
            } else if (dayNumber == 60) {
                this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 60, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
            }
        },
        focus: function() {
            this.readonly = false;
            var me = this;
            if (this.sosoValue && this.sosoValue.trim()) {
                me.sosoValueChange()
            } else {
                this.groupslist.forEach(function(group) {
                    group.devices.forEach(function(device) {
                        device.isOnline = vstore.state.deviceInfos[device.deviceid] ? vstore.state.deviceInfos[device.deviceid].isOnline : false;
                    })
                });
                this.filterData = this.groupslist;
                this.isShowMatchDev = true;
                this.queryDeviceId = '';
                reportDeviceId = null;
            }
        },
        sosoValueChange: function() {
            var me = this;
            var value = this.sosoValue;
            console.log('变了');

            if (this.timeoutIns != null) {
                clearTimeout(this.timeoutIns);
            };

            this.timeoutIns = setTimeout(function() {
                me.filterMethod(value);
            }, 300);
        },
        filterMethod: function(value) {
            var filterData = [];
            value = value.toLowerCase();
            for (var i = 0; i < this.groupslist.length; i++) {

                var group = this.groupslist[i];
                if (
                    group.groupname.toLowerCase().indexOf(value) !== -1 ||
                    group.firstLetter.indexOf(value) !== -1 ||
                    group.pinyin.indexOf(value) !== -1
                ) {
                    group.devices.forEach(function(device) {
                        device.isOnline = vstore.state.deviceInfos[device.deviceid] ? vstore.state.deviceInfos[device.deviceid].isOnline : false;
                    })
                    var devices = group.devices;
                    var obj = {
                        groupname: group.groupname,
                        devices: []
                    };
                    for (var j = 0; j < devices.length; j++) {

                        obj.devices.push(devices[j]);
                        if (j >= 50) {
                            break;
                        }
                    }

                    filterData.push(obj)
                } else {
                    var devices = group.devices;
                    var obj = {
                        groupname: group.groupname,
                        devices: []
                    }
                    for (var j = 0; j < devices.length; j++) {
                        var device = devices[j]
                        var title = device.allDeviceIdTitle

                        device.isOnline = vstore.state.deviceInfos[device.deviceid] ? vstore.state.deviceInfos[device.deviceid].isOnline : false;
                        if (
                            title.toLowerCase().indexOf(value) !== -1 ||
                            device.firstLetter.indexOf(value) !== -1 ||
                            device.pinyin.indexOf(value) !== -1
                        ) {
                            obj.devices.push(device)
                            if (obj.devices.length >= 50) {
                                break;
                            }
                        } else {
                            if (device.remark) {
                                if (device.remark.indexOf(value) !== -1) {
                                    obj.devices.push(device);
                                };
                            };
                        };

                    }
                    if (obj.devices.length) {
                        filterData.push(obj);
                        if (filterData.length >= 50) {
                            break;
                        }
                    };
                };

            };
            this.filterData = filterData;
            if (!this.isShowMatchDev) {
                this.isShowMatchDev = true;
            };
            if (!value) {
                this.queryDeviceId = '';
                reportDeviceId = null;
            }
        },
        sosoSelect: function(item) {
            reportDeviceId = item.deviceid;
            this.sosoValue = item.allDeviceIdTitle;
            this.queryDeviceId = item.deviceid;
            this.isShowMatchDev = false;
        },
        getDeviceTitle: function(deviceid) {
            var title = "";
            this.groupslist.forEach(function(group) {
                var isReturn = false;
                group.devices.forEach(function(device) {
                    if (device.deviceid === deviceid) {
                        isReturn = true;
                        title = device.devicename + '-' + device.deviceid;
                        return false;
                    }
                });
                if (isReturn) { return false };
            });
            return title;
        },
        cleanSelectedDev: function() {
            this.sosoValue = '';
            this.queryDeviceId = '';
            this.filterMethod('');
        }
    },
    watch: {
        currentPageIndex: function() {
            document.body.click();
        }
    },
    mounted: function() {
        var me = this;

        this.$nextTick(function() {
            if (reportDeviceId) {
                me.queryDeviceId = reportDeviceId;
                me.sosoValue = me.getDeviceTitle(reportDeviceId);
            }
        });
        try {
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
                me.chartsIns && me.chartsIns.resize();
            }
        } catch (error) {

        }
    }
}




//  指令查询 DateFormat.longToDateStr(Date.now(),0)
function cmdReport(groupslist) {

    vueInstanse = new Vue({
        el: "#cmd-report",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            groupslist: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), key: "index", width: 90, align: 'center', sortable: true },
                { title: vRoot.$t("alarm.devName"), key: 'deviceName', sortable: true },
                { title: vRoot.$t("user.cmdName"), key: isZh ? 'cmdname' : 'cmdnameen', sortable: true },
                { title: vRoot.$t("reportForm.sendDate"), key: 'cmdtimeStr', sortable: true },
                { title: vRoot.$t("reportForm.content"), key: 'cmdparams', sortable: true },
                { title: isZh ? '发送者' : 'username', key: 'username', sortable: true },
                { title: isZh ? '来源' : 'from', key: 'fromstr' },
                { title: 'ip', key: 'fromip' },
                { title: vRoot.$t("reportForm.sendResult"), key: 'result', sortable: true },
            ],
            tableData: [],
            cmdRecords: []
        },
        mixins: [reportMixin],
        methods: {
            exportData: function() {
                var execlName = vRoot.$t('reportForm.cmdReport') + '-' + this.queryDeviceId;
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("user.cmdName"),
                        vRoot.$t("reportForm.sendDate"),
                        vRoot.$t("reportForm.content"),
                        vRoot.$t("reportForm.sendResult")
                    ]
                ];
                this.cmdRecords.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.deviceName);
                    itemArr.push(isZh ? item.cmdname : item.cmdnameen);
                    itemArr.push(item.cmdtimeStr);
                    itemArr.push(item.cmdparams);
                    itemArr.push(item.result);
                    data.push(itemArr);
                });
                var options = {
                    title: execlName,
                    data: data,
                    dateRange: this.queryDateRange
                }
                new XlsxCls(options).exportExcel();

            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 170 + 40;
                this.posiDetailHeight = wHeight - 144 + 40;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") { return };
                var self = this;
                if (this.isSelectAll === null) {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                    return;
                };
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportCmd(), data, function(resp) {
                    self.loading = false;
                    self.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                    if (resp.status == 0) {
                        if (resp.cmdrecords) {

                            resp.cmdrecords.forEach(function(item, index) {
                                item.index = ++index;
                                item.cmdtimeStr = DateFormat.longToLocalDateTimeStr(item.cmdtime);
                                item.deviceName = vstore.state.deviceInfos[item.deviceid].devicename;
                                item.result = utils.getSendResult(item.sendstatus);
                            });
                            self.cmdRecords = resp.cmdrecords;
                            self.total = self.cmdRecords.length;
                            self.tableData = self.cmdRecords;
                            self.currentPageIndex = 1;
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            onSortChange: function(column) {

            }
        },
        mounted: function() {
            this.groupslist = groupslist;
        }
    });
}
// 位置报表
function posiReport(groupslist) {
    vueInstanse = new Vue({
        el: "#posi-report",
        i18n: utils.getI18n(),
        data: {
            total: 0,
            currentIndex: 1,
            loading: false,
            mapModal: false,
            trackDetailModal: false,
            mapType: null,
            groupslist: [],
            minuteNum: 5,
            tabValue: "lastPosi",
            markerIns: null,
            isSpin: false,
            lastPosiColumns: [
                { title: vRoot.$t("reportForm.index"), key: 'idx', width: 60, align: 'center', fixed: 'left' },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 150, fixed: 'left' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 150 },
                { title: vRoot.$t("reportForm.lon"), key: 'fixedLon', width: 100 },
                { title: vRoot.$t("reportForm.lat"), key: 'fixedLat', width: 100 },
                { title: vRoot.$t("reportForm.direction"), key: 'direction', width: 100 },
                { title: vRoot.$t("reportForm.speed"), key: 'speed', width: 100 },
                { title: vRoot.$t("reportForm.downOfflineDuration"), key: 'downOfflineDuration', width: 180, },
                { title: vRoot.$t("reportForm.date"), key: 'updatetimeStr', width: 160 },
                { title: vRoot.$t("reportForm.status"), key: isZh ? 'strstatus' : 'strstatusen', width: 180 },
                { title: vRoot.$t("reportForm.posiType"), key: 'positype', width: 115 },
                { title: vRoot.$t("reportForm.address"), key: 'address', width: 410 },
                {
                    title: vRoot.$t("bgMgr.action"),
                    key: 'action',
                    width: 190,
                    fixed: 'right',
                    render: function(h, params) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.loading = true;
                                        vueInstanse.trackDetailModal = true;
                                        vueInstanse.deviceName = params.row.devicename;
                                        vueInstanse.querySingleDevTracks(params.row.deviceid, function() {
                                            vueInstanse.loading = false;
                                        });
                                    }
                                }
                            }, vRoot.$t("reportForm.AddressDetails")),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                    disabled: params.row.disabled,
                                },
                                style: {

                                },
                                on: {
                                    click: function() {
                                        vueInstanse.getAddress(0, params);
                                    }
                                }
                            }, vRoot.$t("reportForm.getAddress"))
                        ]);
                    }
                }
            ],
            posiDetailColumns: [
                { title: '#', key: 'index', width: 70, fixed: 'left', },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 150, fixed: 'left', },
                { title: vRoot.$t("reportForm.lon"), key: 'fixedLon', width: 100 },
                { title: vRoot.$t("reportForm.lat"), key: 'fixedLat', width: 100 },
                { title: vRoot.$t("reportForm.direction"), key: 'direction', width: 90 },
                { title: vRoot.$t("reportForm.speed"), key: 'speed', width: 100 },
                { title: vRoot.$t("reportForm.date"), key: 'updatetimeStr', width: 160, sortable: true },
                { title: vRoot.$t("reportForm.status"), key: 'strstatus', width: 180, },
                { title: vRoot.$t("reportForm.posiType"), key: 'positype', width: 115 },
                { title: vRoot.$t("reportForm.address"), key: 'address', width: 600 },
                {
                    title: vRoot.$t("bgMgr.action"),
                    key: 'action',
                    width: 210,
                    fixed: 'right',
                    render: function(h, params) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        utils.showWindowMap(vueInstanse, params);
                                    }
                                }
                            }, vRoot.$t("reportForm.seePosi")),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                    disabled: params.row.disabled,
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.getAddress(1, params);
                                    }
                                }
                            }, vRoot.$t("reportForm.getAddress"))
                        ]);
                    }
                }
            ],
            lastPosiData: [],
            posiDetailData: [],
            tableData: [],
            mapInstance: null,
            deviceName: '',
            idx: 1,
            maxLen: 0,
            queryLoading: false,
            currentIndex: 1,
            total: 0,
            pageSize: 20,

        },
        mixins: [treeMixin],
        methods: {
            changePage: function(index) {
                var offset = index * this.pageSize;
                var start = (index - 1) * this.pageSize;
                this.currentIndex = index;
                this.posiDetailData = this.allPosiDetailData.slice(start, offset);
            },
            getAllTracksAddress: function() {
                var me = this;
                var maxLen = this.posiDetailData.length;
                this.maxLen = maxLen;
                this.queryLoading = true;
                this.idx = 0;
                var hasQueryedLatLon = {};
                this.posiDetailData.forEach(function(track) {
                    var callon = track.fixedLon;
                    var callat = track.fixedLat;
                    var address = LocalCacheMgr.getAddress(callon, callat);
                    if (address == null) {
                        var key = callat + "|" + callon;
                        if (hasQueryedLatLon[key] == null) {
                            hasQueryedLatLon[key] = true;
                            (function(track) {
                                utils.getJiuHuAddressSyn(track.callon, track.callat, function(resp) {
                                    if (resp && resp.address) {
                                        track.address = resp.address;
                                        track.disabled = true;
                                        LocalCacheMgr.setAddress(track.callon, track.callat, track.address);
                                    }
                                    me.idx = me.idx + 1;
                                    if (me.idx >= maxLen) {
                                        me.queryLoading = false;
                                        me.readLocalAddress();
                                    }
                                }, function(e) {
                                    me.idx = me.idx + 1;
                                    if (me.idx >= maxLen) {
                                        me.queryLoading = false;
                                        me.readLocalAddress();
                                    }
                                });
                            })(track);
                        } else {
                            me.idx = me.idx + 1;
                            if (me.idx >= maxLen) {
                                me.queryLoading = false;
                                me.readLocalAddress();
                            }
                        }
                    } else {
                        track.address = address;
                        me.idx = me.idx + 1;
                        if (me.idx >= maxLen) {
                            me.queryLoading = false;
                            me.readLocalAddress();
                        }
                    }
                });
            },
            readLocalAddress: function() {
                this.posiDetailData.forEach(function(track) {
                    var callon = track.fixedLon;
                    var callat = track.fixedLat;
                    var address = LocalCacheMgr.getAddress(callon, callat);
                    if (!track.address) {
                        track.address = address;
                    }
                });
            },
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.lon"),
                        vRoot.$t("reportForm.lat"),
                        vRoot.$t("reportForm.direction"),
                        vRoot.$t("reportForm.speed"),
                        vRoot.$t("reportForm.downOfflineDuration"),
                        vRoot.$t("reportForm.date"),
                        vRoot.$t("reportForm.status"),
                        vRoot.$t("reportForm.posiType"),
                        vRoot.$t("reportForm.address"),
                    ]
                ];
                this.lastPosiData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.fixedLon);
                    itemArr.push(item.fixedLat);
                    itemArr.push(item.direction);
                    itemArr.push(item.speed);
                    itemArr.push(item.downOfflineDuration);
                    itemArr.push(item.updatetimeStr);
                    itemArr.push(item.isZh ? item.strstatus : item.strstatusen);
                    itemArr.push(item.positype);
                    itemArr.push(item.address);

                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.posiReport'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            exportDetailData: function() {
                var data = [

                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.lon"),
                        vRoot.$t("reportForm.lat"),
                        vRoot.$t("reportForm.direction"),
                        vRoot.$t("reportForm.speed"),
                        vRoot.$t("reportForm.date"),
                        vRoot.$t("reportForm.status"),
                        vRoot.$t("reportForm.posiType"),
                        vRoot.$t("reportForm.address"),
                    ]
                ];

                this.allPosiDetailData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.fixedLon);
                    itemArr.push(item.fixedLat);
                    itemArr.push(item.direction);
                    itemArr.push(item.speed);
                    itemArr.push(item.updatetimeStr);
                    itemArr.push(item.isZh ? item.strstatus : item.strstatusen);
                    itemArr.push(item.positype);
                    itemArr.push(item.address);
                    data.push(itemArr);
                });
                var options = {
                    title: isZh ? this.deviceName + " -位置详细报表" : this.deviceName + "-PosiDetailReport",
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 130;
                this.posiDetailHeight = wHeight - 190;
            },
            onClickQuery: function() {
                var me = this;
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length) {

                    this.loading = true;
                    this.getLastPosition(deviceids, function() {
                        me.loading = false;
                    });
                } else {
                    me.$Message.error(me.$t('reportForm.selectDevTip'));
                }

            },
            getLastPosition: function(deviceIds, callback) {
                var me = this;
                var url = myUrls.lastPosition();
                var data = {
                    username: userName,
                    deviceids: deviceIds
                }
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        if (resp.records) {
                            var newCored = [];
                            resp.records.forEach(function(item, index) {
                                if (item) {
                                    var time = Date.now() - item.updatetime;
                                    var deviceid = item.deviceid;
                                    item.idx = index + 1;
                                    item.devicename = vstore.state.deviceInfos[deviceid].devicename;
                                    item.updatetimeStr = DateFormat.longToLocalDateTimeStr(item.updatetime);
                                    item.fixedLon = item.callon.toFixed(5);
                                    item.fixedLat = item.callat.toFixed(5);
                                    var address = LocalCacheMgr.getAddress(item.fixedLon, item.fixedLat);
                                    item.address = address ? address : '';
                                    item.disabled = address ? true : false;
                                    newCored.push(item);
                                    item.positype = utils.getPosiType(item);
                                    item.direction = utils.getCarDirection(item.course);
                                    item.downOfflineDuration = time > 600000 ? utils.timeStamp(Date.now() - item.updatetime) : vRoot.$t('monitor.online');
                                    item.speed = item.speed == 0 ? item.speed : (item.speed / 1000).toFixed(2) + "h/km";
                                }
                            });

                            me.lastPosiData = newCored;

                        } else {

                        }
                    }
                })
                callback();
            },
            querySingleDevTracks: function(deviceid, callback) {
                var me = this;
                var url = myUrls.queryTracks();
                var data = {
                    "deviceid": deviceid,
                    "begintime": this.dateVal[0] + " 00:00:00",
                    "endtime": this.dateVal[1] + " 23:59:00",
                    'interval': this.minuteNum * 60,
                    'timezone': timeDifference
                };

                utils.sendAjax(url, data, function(resp) {
                    me.queryDateRange = data.begintime + ' - ' + data.endtime;
                    if (resp.status === 0) {
                        if (resp.records && resp.records.length) {
                            var newArr = [];
                            var devicename = vstore.state.deviceInfos[deviceid].devicename;
                            resp.records.sort(function(a, b) {
                                return b.updatetime - a.updatetime;
                            });
                            resp.records.forEach(function(item, idx) {
                                var fixedLon = item.callon.toFixed(5);
                                var fixedLat = item.callat.toFixed(5);
                                var address = LocalCacheMgr.getAddress(fixedLon, fixedLat);
                                newArr.push({
                                    index: idx + 1,
                                    deviceid: "\t" + deviceid,
                                    devicename: devicename,
                                    updatetimeStr: "\t" + DateFormat.longToLocalDateTimeStr(item.updatetime),
                                    callon: item.callon,
                                    callat: item.callat,
                                    fixedLon: fixedLon,
                                    fixedLat: fixedLat,
                                    strstatus: item.strstatus,
                                    strstatusen: item.strstatusen,
                                    positype: utils.getPosiType(item),
                                    address: address ? address : '',
                                    disabled: address ? true : false,
                                    direction: item.direction = utils.getCarDirection(item.course),
                                    speed: item.speed == 0 ? item.speed : (item.speed / 1000).toFixed(2) + "h/km"
                                })
                            });
                            me.allPosiDetailData = newArr;
                            me.posiDetailData = newArr.slice(0, me.pageSize);
                            me.total = newArr.length;
                            me.currentIndex = 1;

                        } else {
                            me.allPosiDetailData = [];
                            me.posiDetailData = [];
                            me.currentIndex = 1;
                            me.total = 0;
                        }
                    } else {
                        me.allPosiDetailData = [];
                        me.posiDetailData = [];
                        me.currentIndex = 1;
                        me.total = 0;
                    }
                    callback();
                });
            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('posi-map');
            },
            getAddress: function(type, params) {
                var me = this;
                var row = params.row;
                var index = params.index;
                utils.queryAddress(row, function(address) {
                    if (type === 0) {
                        me.lastPosiData[index].address = address;
                        me.lastPosiData[index].disabled = true;
                    } else if (type === 1) {
                        me.posiDetailData[index].address = address;
                        me.posiDetailData[index].disabled = true;
                    }
                    LocalCacheMgr.setAddress(row.fixedLon, row.fixedLat, address);
                });
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        watch: {
            trackDetailModal: function() {
                if (!this.trackDetailModal) {
                    this.posiDetailData = [];
                }
            }
        },
        mounted: function() {
            var me = this;
            this.mapType = utils.getMapType();
            this.initMap();
            this.allPosiDetailData = [];
            this.queryDevicesTree();
        }
    })
}

// 里程详单
function reportMileageDetail(groupslist) {
    vueInstanse = new Vue({
        el: '#mileage-detail',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            isShowMatchDev: true,
            columns: [
                { title: vRoot.$t("alarm.devName"), key: 'deviceName' },
                { title: vRoot.$t("reportForm.date"), key: 'statisticsday', sortable: true },
                { title: vRoot.$t("reportForm.minMileage"), key: 'mintotaldistance', sortable: true },
                { title: vRoot.$t("reportForm.maxMileage"), key: 'maxtotaldistance', sortable: true },
                { title: vRoot.$t("reportForm.totalMileage"), key: 'totaldistance', sortable: true },
            ],
            tableData: []
        },
        methods: {
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("reportForm.date"),
                        vRoot.$t("reportForm.minMileage"),
                        vRoot.$t("reportForm.maxMileage"),
                        vRoot.$t("reportForm.totalMileage"),
                    ]
                ];
                var len = this.tableData.length - 1;
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    if (len == index) {
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push(item.totaldistance);
                    } else {
                        itemArr.push(index + 1);
                        itemArr.push(item.deviceName);
                        itemArr.push(item.statisticsday);
                        itemArr.push(item.mintotaldistance);
                        itemArr.push(item.maxtotaldistance);
                        itemArr.push(item.totaldistance);
                    }

                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.reportmileagesummary') + '-' + this.queryDeviceId,
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            onChange: function(value) {
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 130;
                this.posiDetailHeight = wHeight - 104;
            },
            onClickQuery: function() {
                if (this.queryDeviceId) {
                    var me = this;
                    var url = myUrls.reportMileageDetail();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceid: this.queryDeviceId
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        if (resp.status === 0) {
                            if (resp.records.length) {
                                var total = 0;
                                resp.records.forEach(function(item) {
                                    total += item.totaldistance;
                                    item.deviceName = vstore.state.deviceInfos[me.queryDeviceId].devicename;
                                    item.mintotaldistance = utils.getMileage(item.mintotaldistance);
                                    item.maxtotaldistance = utils.getMileage(item.maxtotaldistance);
                                    item.totaldistance = utils.getMileage(item.totaldistance);
                                });
                                resp.records.push({
                                    totaldistance: me.$t("reportForm.total") + utils.getMileage(total),
                                });
                                me.tableData = resp.records;
                            } else {
                                me.tableData = [];
                            };
                        } else {
                            me.tableData = [];
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            }
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}



function mileageMonthReport(groupslist) {
    vueInstanse = new Vue({
        el: '#month-mileage',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            month: '',
            columns: [],
            tableData: [],
            currentIndex: 1,
            dateOptions: {
                disabledDate: function(date) {
                    return (date && date.valueOf()) > Date.now();
                }
            },
        },
        methods: {
            exportData: function() {

                // var columns = [
                //     { key: 'index', width: 70, title: vRoot.$t("reportForm.index"), fixed: 'left' },
                //     { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 100, fixed: 'left' },
                //     { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 100, fixed: 'left' },
                //     { title: vRoot.$t("reportForm.totalMileage"), key: 'totaldistance', sortable: true, width: 100, fixed: 'left' },
                // ];



                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("user.cmdName"),
                        vRoot.$t("reportForm.totalMileage"),
                    ]
                ];

                var day = this.getTheMonthDays(this.month);
                console.log('day', day);
                for (var i = 1; i <= day; i++) {
                    data[0].push(i);
                }
                this.records.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.totaldistance);
                    for (var i = 1; i <= day; i++) {
                        itemArr.push(item['day' + i]);
                    }
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.mileageMonthReport') + '_' + DateFormat.format(this.month, 'yyyy-MM'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 175;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportMileageMonth();
                    var yearmonth = DateFormat.format(this.month, 'yyyy-MM');
                    var yearmonthArr = yearmonth.split("-");
                    var data = {
                        year: Number(yearmonthArr[0]),
                        month: Number(yearmonthArr[1]),
                        offset: timeDifference,
                        deviceids: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        // console.log(resp);
                        me.loading = false;
                        if (resp.status === 0) {
                            var dayLen = me.getTheMonthDays(me.month);
                            if (resp.devices.length) {
                                resp.devices.forEach(function(item, idx) {
                                    item.index = idx + 1;

                                    var deviceid = item.deviceid;
                                    var records = item.records;
                                    var totaldistance = 0;
                                    for (var j = 0; j < dayLen; j++) {
                                        var day = records[j];
                                        if (day) {
                                            var key = day.statisticsday.split('-')[2];
                                            var distance = day.maxtotaldistance - day.mintotaldistance;
                                            totaldistance += distance;
                                            item['day' + String(parseInt(key))] = utils.getMileage(distance);
                                        }
                                    }
                                    for (var k = 0; k < dayLen; k++) {
                                        var key = 'day' + (k + 1);
                                        if (!item[key]) {
                                            item[key] = '-';
                                        }
                                    }
                                    item.devicename = "\t" + (vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid);
                                    item.deviceid = "\t" + deviceid;
                                    item.totaldistance = utils.getMileage(totaldistance);
                                });
                                me.records = resp.devices;
                                me.tableData = me.records.slice(0, 20);
                                me.total = me.records.length;

                            } else {
                                me.tableData = [];
                            };
                            me.currentIndex = 1;
                        } else {
                            me.tableData = [];
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            getTheMonthDays: function(date) {
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                year = month == 12 ? year + 1 : year;
                month = month == 12 ? 1 : month;
                return new Date(new Date(year, month, 1) - 1).getDate();
            },
        },
        watch: {
            month: function(newMonth) {

                var columns = [
                    { key: 'index', width: 70, title: vRoot.$t("reportForm.index"), fixed: 'left' },
                    { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 100, fixed: 'left' },
                    { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 100, fixed: 'left' },
                    { title: vRoot.$t("reportForm.totalMileage"), key: 'totaldistance', sortable: true, width: 100, fixed: 'left' },
                ];

                var day = this.getTheMonthDays(newMonth);

                for (var i = 1; i <= day; i++) {
                    columns.push({
                        key: 'day' + i,
                        title: i,
                        width: 80,
                        sortable: true,
                    })
                }

                this.columns = columns;
            },
        },
        mounted: function() {
            var me = this;
            me.month = new Date();
            me.records = [];
            me.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}



function deviceMsg(groupslist) {
    vueInstanse = new Vue({
        el: '#device-msg',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            lastTableHeight: 100,
            groupslist: [],
            columns: [
                { key: 'index', width: 70, title: vRoot.$t("reportForm.index") },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 160 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 160 },
                { title: vRoot.$t("reportForm.date"), key: 'createtimeStr', width: 160 },
                { title: isZh ? '消息类型' : 'Msg Type', key: 'msgtype', width: 100 },
                { title: isZh ? '消息内容' : 'Content', key: 'content' },
            ],
            tableData: [],
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.date"),
                        isZh ? '消息类型' : 'Msg Type',
                        isZh ? '消息内容' : 'Content',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.createtimeStr);
                    itemArr.push(item.msgtype);
                    itemArr.push(item.content);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.deviceMsg'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 130;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportDeviceMsg();

                    var data = {
                        devices: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        console.log(resp);
                        me.loading = false;

                        if (resp.msgs) {
                            resp.msgs.forEach(function(item, index) {
                                item.index = index + 1;
                                var deviceid = item.deviceid;
                                item.devicename = "\t" + (vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid);
                                item.createtimeStr = DateFormat.longToLocalDateTimeStr(item.createtime);
                            });
                            me.tableData = resp.msgs;
                        } else {
                            me.tableData = [];
                        }



                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            getTheMonthDays: function(date) {
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                year = month == 12 ? year + 1 : year;
                month = month == 12 ? 1 : month;
                return new Date(new Date(year, month, 1) - 1).getDate();
            },
        },

        mounted: function() {
            var me = this;
            me.records = [];
            me.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}

function pushTextReport(groupslist) {
    vueInstanse = new Vue({
        el: '#push-text-report',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            keyword: '',
            lastTableHeight: 100,
            groupslist: [],
            columns: [
                { key: 'index', width: 70, title: vRoot.$t("reportForm.index") },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 160 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 160 },
                { title: vRoot.$t("reportForm.date"), key: 'createtimeStr', width: 160 },

                {
                    title: isZh ? '用户名' : 'Username',
                    width: 120,
                    render: function(h, params) {
                        var creater = params.row.username;
                        return h('Poptip', {
                            props: {
                                confirm: false,
                                // title: '上级信息',
                            },
                            style: {
                                marginRight: '5px',
                            },
                        }, [
                            h('Button', {
                                props: {
                                    type: 'info',
                                    size: 'small'
                                },
                                on: {
                                    click: function() {

                                        var url = myUrls.queryParents();
                                        var data = {
                                            currentuser: creater
                                        }
                                        utils.sendAjax(url, data, function(resp) {
                                            var createrrecords = [];
                                            var records = resp.records;
                                            records.forEach(function(item) {
                                                createrrecords.push(h('div', {}, item.username + '(' + utils.getUserTypeDesc(item.usertype) + ')'))
                                            });
                                            params.row.createrrecords = createrrecords;
                                        })
                                    }
                                }
                            }, creater),
                            h(
                                'div', {
                                    slot: 'content',
                                    attrs: {
                                        slot: "content"
                                    }
                                }, params.row.createrrecords
                            )
                        ]);
                    }
                },

                { title: isZh ? '消息内容' : 'Content', key: 'cmdparams' },
                { title: isZh ? '结果' : 'Result', width: 180, key: 'result' },
            ],
            tableData: [],
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.date"),
                        isZh ? '用户名' : 'Username',
                        isZh ? '消息内容' : 'Content',
                        isZh ? '结果' : 'Result',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.createtimeStr);
                    itemArr.push(item.username);
                    itemArr.push(item.cmdparams);
                    itemArr.push(item.result);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.pushTextReport'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 130;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportPushText();

                    var data = {
                        devices: deviceids,
                        keyword: this.keyword
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;

                        if (resp.records) {
                            resp.records.forEach(function(item, index) {
                                item.index = index + 1;
                                var deviceid = item.deviceid;
                                item.createrrecords = [];
                                item.devicename = "\t" + (vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid);
                                item.createtimeStr = DateFormat.longToLocalDateTimeStr(item.cmdtime);
                                item.result = utils.getSendResult(item.sendstatus);
                            });
                            me.tableData = resp.records;
                        } else {
                            me.tableData = [];
                        }



                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            getTheMonthDays: function(date) {
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                year = month == 12 ? year + 1 : year;
                month = month == 12 ? 1 : month;
                return new Date(new Date(year, month, 1) - 1).getDate();
            },
        },

        mounted: function() {
            var me = this;
            me.records = [];
            me.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


function drivingRecordReport() {
    vueInstanse = new Vue({
        el: "#driving-record-report",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            loadingData: false,
            mapType: null,
            groupslist: [],
            markerIns: null,
            isSpin: false,
            columns: [
                { title: vRoot.$t("reportForm.index"), key: 'idx', width: 60 },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 80,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    editObject = params.row;
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getDetailTableData(params.row);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.detailed") + "]")
                    }
                },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 150 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 150 },
                { title: vRoot.$t("reportForm.startDate"), key: 'starttimeStr', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.endDate"), key: 'endtimeStr', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.duration") + '(H)', key: 'durationtime', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.startDistance") + '(Km)', key: 'startdistance', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.endDistance") + '(Km)', key: 'enddistance', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.durationDistance") + '(Km)', key: 'durationdistance', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.averageSpeed") + '(Km)', key: 'avgspeed', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.maxSpeed") + '(Km/h)', key: 'maxspeed', width: 140, sortable: true },
                { title: vRoot.$t("reportForm.startAddress"), key: 'startaddress', width: 230 },
                { title: vRoot.$t("reportForm.endAddress"), key: 'endaddress', width: 230 },
                { title: vRoot.$t("reportForm.start_lon_lat"), key: 'start_lon_lat', width: 145 },
                { title: vRoot.$t("reportForm.end_lon_lat"), key: 'end_lon_lat', width: 145 },

            ],
            tableData: [],
            columnsDetails: [
                { title: vRoot.$t("reportForm.index"), key: 'idx', width: 60 },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 150 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 150 },
                { title: vRoot.$t("reportForm.startDate"), key: 'starttimeStr', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.endDate"), key: 'endtimeStr', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.duration") + '(H)', key: 'durationtime', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.startDistance") + '(Km)', key: 'startdistance', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.endDistance") + '(Km)', key: 'enddistance', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.durationDistance") + '(Km)', key: 'durationdistance', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.averageSpeed") + '(Km)', key: 'avgspeed', width: 130, sortable: true },
                { title: vRoot.$t("reportForm.maxSpeed") + '(Km/h)', key: 'maxspeed', width: 140, sortable: true },
                { title: vRoot.$t("reportForm.startAddress"), key: 'startaddress', width: 230 },
                { title: vRoot.$t("reportForm.endAddress"), key: 'endaddress', width: 230 },
                { title: vRoot.$t("reportForm.start_lon_lat"), key: 'start_lon_lat', width: 145 },
                { title: vRoot.$t("reportForm.end_lon_lat"), key: 'end_lon_lat', width: 145 },
            ],
            tableDataDetails: [],
            treeData: [],
            tableHeight: 100,
            activeTab: 'tabTotal',
            limitspeed: '5'
        },
        mixins: [treeMixin],
        methods: {
            exportData: function() {
                var me = this;
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.duration") + '(H)',
                        vRoot.$t("reportForm.durationDistance") + '(Km)',
                        vRoot.$t("reportForm.startDate"),
                        vRoot.$t("reportForm.endDate"),
                        vRoot.$t("reportForm.startDistance") + '(Km)',
                        vRoot.$t("reportForm.endDistance") + '(Km)',
                        vRoot.$t("reportForm.averageSpeed") + '(Km)',
                        vRoot.$t("reportForm.maxSpeed") + '(Km/h)',
                        vRoot.$t("reportForm.startAddress"),
                        vRoot.$t("reportForm.endAddress"),
                        vRoot.$t("reportForm.start_lon_lat"),
                        vRoot.$t("reportForm.end_lon_lat")
                    ]
                ];



                if (this.activeTab == 'tabTotal') {
                    if (this.tableData.length == 0) {
                        vRoot.$Message.error(isZh ? '没有数据' : 'No Data');
                        return;
                    }
                    var deviceids = [];
                    this.tableData.forEach(function(item, index) {
                        deviceids.push(item.deviceid);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.drivingStatistics'),
                        dateRange: this.queryDateRange,
                    }


                    var url = myUrls.reportDrivingRecord();
                    var postData = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids,
                        limitspeed: Number(this.limitspeed),
                        reporttype: 1
                    };
                    this.loadingData = true;
                    utils.sendAjax(url, postData, function(resp) {
                        me.loadingData = false;
                        if (resp != null && resp.status == 0) {

                            var summaries = resp.summaries;
                            if (summaries != null) {
                                //merge the title
                                var merges = [];
                                var toMergeRow = 3;
                                summaries.forEach(function(summary, indexSummary) {
                                    var records = summary.records;
                                    var deviceid = summary.deviceid;

                                    summary.devicename = vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid;

                                    if (records != null && records.length > 0) {

                                        summary.starttimeStr = DateFormat.longToLocalDateTimeStr(summary.starttime);
                                        summary.endtimeStr = DateFormat.longToLocalDateTimeStr(summary.endtime);
                                        summary.durationtime = Number((summary.durationtime / 1000 / 3600).toFixed(2));
                                        summary.durationdistance = Number((summary.durationdistance / 1000).toFixed(2));

                                        var toMergeStartRow = toMergeRow;
                                        var toMergeEndRow = toMergeRow;
                                        records.forEach(function(record, indexRecord) {
                                            record.starttimeStr = DateFormat.longToLocalDateTimeStr(record.starttime);
                                            record.endtimeStr = DateFormat.longToLocalDateTimeStr(record.endtime);
                                            record.durationtime = Number((record.durationtime / 1000 / 3600).toFixed(2));
                                            record.startdistance = Number((record.startdistance / 1000).toFixed(2));
                                            record.enddistance = Number((record.enddistance / 1000).toFixed(2));
                                            record.durationdistance = Number((record.durationdistance / 1000).toFixed(2));
                                            record.avgspeed = Number((record.avgspeed / 1000).toFixed(2));
                                            record.maxspeed = Number((record.maxspeed / 1000).toFixed(2));
                                            record.start_lon_lat = record.slon.toFixed(5) + ',' + record.slat.toFixed(5);
                                            record.end_lon_lat = record.elon.toFixed(5) + ',' + record.elat.toFixed(5);
                                            var itemArr = [];
                                            itemArr.push(indexSummary + 1);
                                            itemArr.push(summary.devicename);
                                            itemArr.push(summary.deviceid);
                                            itemArr.push(summary.durationtime);
                                            itemArr.push(summary.durationdistance);
                                            itemArr.push(record.starttimeStr);
                                            itemArr.push(record.endtimeStr);
                                            itemArr.push(record.startdistance);
                                            itemArr.push(record.enddistance);
                                            itemArr.push(record.avgspeed);
                                            itemArr.push(record.maxspeed);
                                            itemArr.push(record.startaddress);
                                            itemArr.push(record.endaddress);
                                            itemArr.push(record.start_lon_lat);
                                            itemArr.push(record.end_lon_lat);
                                            data.push(itemArr);
                                            toMergeRow++;
                                            toMergeEndRow++;
                                        });
                                        //合并编号
                                        var merge = {
                                            s: {
                                                r: toMergeStartRow,
                                                c: 0
                                            },
                                            e: {
                                                r: toMergeEndRow - 1,
                                                c: 0,
                                            },
                                        };
                                        merges.push(merge);
                                        //合并名字
                                        merge = {
                                            s: {
                                                r: toMergeStartRow,
                                                c: 1
                                            },
                                            e: {
                                                r: toMergeEndRow - 1,
                                                c: 1,
                                            },
                                        };
                                        merges.push(merge);
                                        //合并设备id
                                        merge = {
                                            s: {
                                                r: toMergeStartRow,
                                                c: 2
                                            },
                                            e: {
                                                r: toMergeEndRow - 1,
                                                c: 2,
                                            },
                                        };
                                        merges.push(merge);
                                        //合并时长
                                        merge = {
                                            s: {
                                                r: toMergeStartRow,
                                                c: 3
                                            },
                                            e: {
                                                r: toMergeEndRow - 1,
                                                c: 3,
                                            },
                                        };
                                        merges.push(merge);
                                        //合并公里数
                                        merge = {
                                            s: {
                                                r: toMergeStartRow,
                                                c: 4
                                            },
                                            e: {
                                                r: toMergeEndRow - 1,
                                                c: 4,
                                            },
                                        };
                                        merges.push(merge);
                                    } else {
                                        var itemArr = [];
                                        itemArr.push(indexSummary + 1);
                                        itemArr.push(summary.devicename);
                                        itemArr.push(summary.deviceid);
                                        itemArr.push(0);
                                        itemArr.push(0);
                                        itemArr.push(0);
                                        itemArr.push(0);
                                        itemArr.push(0);
                                        itemArr.push(0);
                                        itemArr.push(0);
                                        itemArr.push(0);
                                        itemArr.push('-');
                                        itemArr.push('-');
                                        itemArr.push('-');
                                        itemArr.push('-');
                                        data.push(itemArr);
                                        toMergeRow++;
                                    }

                                });
                                merges.push({
                                    s: {
                                        r: 0,
                                        c: 0
                                    },
                                    e: {
                                        r: 0,
                                        c: data[2].length - 1
                                    },
                                })
                                options.merges = merges;
                            }
                        }
                        options.data = data;

                        new XlsxCls(options).exportExcel();
                    })
                } else {

                    if (this.tableDataDetails.length == 0) {
                        vRoot.$Message.error(isZh ? '没有数据' : 'No Data');
                        return;
                    }

                    this.tableDataDetails.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.durationtime);
                        itemArr.push(item.startdistance);
                        itemArr.push(item.starttimeStr);
                        itemArr.push(item.endtimeStr);
                        itemArr.push(item.enddistance);
                        itemArr.push(item.durationdistance);
                        itemArr.push(item.avgspeed);
                        itemArr.push(item.maxspeed);
                        itemArr.push(item.startaddress);
                        itemArr.push(item.endaddress);
                        itemArr.push(item.start_lon_lat);
                        itemArr.push(item.end_lon_lat);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.drivingStatistics') + '-' + editObject.deviceid,
                        data: data,
                        dateRange: this.queryDetailDateRange,

                    }
                    new XlsxCls(options).exportExcel();
                }


            },
            getDetailTableData: function(row) {
                var me = this;
                // this.tableDataDetails = row.records;
                me.loading = true;
                var url = myUrls.reportDrivingRecord();
                var data = row.data;
                this.queryDetailDateRange = data.startday + ' - ' + data.endday;
                utils.sendAjax(url, data, function(resp) {
                    me.loading = false;
                    if (resp.status == 0) {
                        var tableDataDetails = [];
                        resp.summaries.forEach(function(item) {
                            var deviceid = item.deviceid;
                            var devicename = vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid;
                            if (item.records) {
                                item.records.forEach(function(record, j) {
                                    record.idx = j + 1;
                                    record.deviceid = deviceid;
                                    record.devicename = devicename;
                                    record.starttimeStr = '\t' + DateFormat.longToLocalDateTimeStr(record.starttime);
                                    record.endtimeStr = '\t' + DateFormat.longToLocalDateTimeStr(record.endtime);
                                    record.durationtime = Number((record.durationtime / 1000 / 3600).toFixed(2));
                                    record.startdistance = Number((record.startdistance / 1000).toFixed(2));
                                    record.enddistance = Number((record.enddistance / 1000).toFixed(2));
                                    record.durationdistance = Number((record.durationdistance / 1000).toFixed(2));
                                    record.avgspeed = Number((record.avgspeed / 1000).toFixed(2));
                                    record.maxspeed = Number((record.maxspeed / 1000).toFixed(2));
                                    record.start_lon_lat = record.slon.toFixed(5) + ',' + record.slat.toFixed(5);
                                    record.end_lon_lat = record.elon.toFixed(5) + ',' + record.elat.toFixed(5);
                                })
                            }
                            tableDataDetails = item.records ? item.records : [];
                        });
                        me.tableDataDetails = tableDataDetails;
                        me.polygonLayer.clear();
                        if (me.markerLayer != null) {
                            me.mapInstance.removeLayer(me.markerLayer);
                        }
                        if (me.tableDataDetails.length) {
                            var first = me.tableDataDetails[0];
                            first._highlight = true;
                            me.querySingleDevTracks(first);
                        }
                    }
                });

            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 178;
            },
            querySingleDevTracks: function(row) {
                var me = this;
                var url = myUrls.queryTracks();
                var data = {
                    deviceid: row.deviceid,
                    begintime: row.starttimeStr,
                    endtime: row.endtimeStr,
                    timezone: timeDifference
                };
                me.extents = [];
                utils.sendAjax(url, data, function(resp) {
                    me.isSpin = false;
                    if (resp.status == 0) {
                        var records = resp.records;
                        if (records && records.length) {
                            utils.markersAndLineLayerToMap(me, records);
                            me.redrawCharts(records);
                            // me.drawFence(row.points);
                            // var polygon = new maptalks.Polygon(me.extents);
                            // me.mapInstance.fitExtent(polygon.getExtent(), 0);
                        } else {
                            me.$Message.error(isZh ? '没有轨迹' : 'No Data');
                        }
                    }
                }, function() {
                    me.isSpin = false;
                });

            },
            onClickQuery: function() {
                var me = this;
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length) {

                    this.activeTab = 'tabTotal';
                    this.loading = true;
                    var url = myUrls.reportDrivingRecord();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids,
                        limitspeed: Number(this.limitspeed),
                        reporttype: 0
                    };
                    utils.sendAjax(url, data, function(resp) {

                        me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                        me.loading = false;
                        if (resp.status == 0) {
                            resp.summaries.forEach(function(item, i) {
                                item.idx = i + 1;
                                var deviceid = item.deviceid;
                                var devicename = vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid;
                                item.devicename = devicename;
                                item.starttimeStr = item.starttime > 0 ? DateFormat.longToLocalDateTimeStr(item.starttime) : 0;
                                item.endtimeStr = item.endtime > 0 ? DateFormat.longToLocalDateTimeStr(item.endtime) : 0;
                                item.durationtime = Number((item.durationtime / 1000 / 3600).toFixed(2));
                                item.startdistance = Number((item.startdistance / 1000).toFixed(2));
                                item.enddistance = Number((item.enddistance / 1000).toFixed(2));
                                item.durationdistance = Number((item.durationdistance / 1000).toFixed(2));
                                item.avgspeed = Number((item.avgspeed / 1000).toFixed(2));
                                item.maxspeed = Number((item.maxspeed / 1000).toFixed(2));
                                item.start_lon_lat = item.slon.toFixed(5) + ',' + item.slat.toFixed(5);
                                item.end_lon_lat = item.elon.toFixed(5) + ',' + item.elat.toFixed(5);
                                var sendData = deepClone(data);
                                sendData.deviceids = [deviceid];
                                sendData.reporttype = 1;
                                sendData.startday = item.starttimeStr;
                                sendData.endday = item.endtimeStr;
                                item.data = sendData;
                            })
                            me.tableData = resp.summaries;
                        };
                    }, function() {
                        me.loading = false;
                    })

                } else {
                    me.$Message.error(me.$t('reportForm.selectDevTip'));
                }

            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('trip-map');
                this.polygonLayer = new maptalks.VectorLayer('vector').addTo(this.mapInstance);
            },
            addFenceLabel: function(name, lon_lat) {
                new maptalks.Label(name, lon_lat, {
                    'textSymbol': {
                        'textFaceName': 'monospace',
                        'textFill': '#34495e',
                        'textHaloFill': '#fff',
                        'textHaloRadius': 4,
                        'textSize': 12,
                        'textWeight': 'bold',
                        'textVerticalAlignment': 'top'
                    }
                }).addTo(this.polygonLayer);
            },
            drawFence: function(points) {
                this.polygonLayer.clear();
                var me = this;
                var isBMap = utils.getMapType() == 'bMap';
                var symbol = {
                    'lineColor': '#e4393c',
                    'lineWidth': 2,
                    'polygonFill': 'rgb(135,196,240)',
                    'polygonOpacity': 0
                };
                var isDrawing = {};
                points.forEach(function(point) {

                    var element = point.geosystemrecord;
                    var georecorduuid = element.georecorduuid;
                    if (!isDrawing[georecorduuid]) {
                        switch (element.type) {
                            case 1:
                                if (isBMap) {
                                    var lon_lat = wgs84tobd09(element.lon1, element.lat1);
                                } else {
                                    var lon_lat = wgs84togcj02(element.lon1, element.lat1);
                                }

                                var point = {
                                    x: lon_lat[0],
                                    y: lon_lat[1]
                                }
                                var circle = new maptalks.Circle(point, element.radius1, {
                                    symbol: symbol
                                });
                                circle.addTo(me.polygonLayer);
                                var extent = circle.getExtent();
                                me.extents.push({
                                    x: extent.xmax,
                                    y: extent.ymax,
                                })
                                me.extents.push({
                                    x: extent.xmin,
                                    y: extent.ymin,
                                })
                                me.addFenceLabel(element.name, lon_lat);
                                break;
                            case 2:
                                var lon_lat_s = [];
                                if (isBMap) {
                                    var lon_lat = wgs84tobd09(element.lon1, element.lat1);
                                    lon_lat_s = wgs84sToBdPoints(JSON.parse(element.points2));
                                } else {
                                    var lon_lat = wgs84togcj02(element.lon1, element.lat1);
                                    lon_lat_s = wgs84sToGooglePoints(JSON.parse(element.points2));
                                }
                                var polygon = new maptalks.Polygon(lon_lat_s, {
                                    symbol: symbol
                                });
                                polygon.addTo(me.polygonLayer);
                                var extent = polygon.getExtent();
                                me.extents.push({
                                    x: extent.xmax,
                                    y: extent.ymax,
                                })
                                me.extents.push({
                                    x: extent.xmin,
                                    y: extent.ymin,
                                })
                                me.addFenceLabel(element.name, lon_lat);
                                break;
                        }
                        isDrawing[georecorduuid] = true;

                    }

                });

            },
            redrawCharts: function(tracks) {
                var me = this;
                var records = tracks;
                var distance = []; //总里程;
                var recvtime = []; //时间
                var veo = []; //速度
                var totalad = [];
                var notRunOil = [];
                var oil1 = [];
                var oil2 = [];
                var oil3 = [];
                var oil4 = [];
                var devStates = [];
                var devReissue = [];
                this.disMin = 0;
                var totalDistanceMin = 0;
                records.forEach(function(item, index) {
                    item.totaldistance = item.totaldistance / 1000;
                    if (index == 0) {
                        totalDistanceMin = item.totaldistance;
                        firstDistance = totalDistanceMin;
                    }

                    oil1.push(item.ad0 / 100);
                    oil2.push(item.ad1 / 100);
                    oil3.push(item.ad2 / 100);
                    oil4.push(item.ad3 / 100);
                    devStates.push(item.strstatus);
                    devReissue.push(item.reissue == 0 ? me.$t('header.no') : me.$t('header.yes'));
                    totalad.push(item.totalad / 100);
                    notRunOil.push(item.totalnotrunningad / 100);
                    recvtime.push(DateFormat.longToLocalDateTimeStr(item.updatetime));
                    veo.push(Number((item.speed / 1000).toFixed(2)));
                    distance.push(Number((item.totaldistance - totalDistanceMin).toFixed(3)));
                });



                this.distance = distance;
                this.recvtime = recvtime;
                this.veo = veo;
                this.totalad = totalad;
                this.notRunOil = notRunOil;
                this.oil1 = oil1;
                this.oil2 = oil2;
                this.oil3 = oil3;
                this.oil4 = oil4;
                this.devStates = devStates;
                this.devReissue = devReissue;

                this.chartsIns.setOption(this.getChartsOption());
            },
            getChartsOption: function() {

                var totoil = vRoot.$t('reportForm.totalOil');
                var notRunTotalad = vRoot.$t('reportForm.notRunTotalad');
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');
                var status = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t('reportForm.reissue');

                return {
                    grid: {
                        top: 40,
                        left: 60,
                        right: 60,
                        bottom: 20,
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName && v[i].seriesName != time) {
                                    if (v[i].seriesName == dis) {
                                        var currentDistance = v[i].value;
                                        var totalDistance = ((Number(currentDistance) + firstDistance / 1000)).toFixed(2);
                                        data += v[i].seriesName + ' : ' + currentDistance + "km(T:" + totalDistance + 'km)<br/>';

                                    } else if (v[i].seriesName == notRunTotalad || v[i].seriesName == totoil || v[i].seriesName == usoil1 || v[i].seriesName == usoil2 || v[i].seriesName == usoil3 || v[i].seriesName == usoil4) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'L<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else {
                                        data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, totoil, notRunTotalad, usoil1, usoil2, usoil3, usoil4],
                        selected: this.selectedLegend,
                        x: 'left',
                    },

                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: speed,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: dis, //
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.veo
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distance
                        }, {
                            smooth: true,
                            name: totoil,
                            type: 'line',
                            symbol: 'none',
                            color: '#C1232B',
                            data: this.totalad,
                            markPoint: {
                                data: this.markPointData,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: notRunTotalad,
                            type: 'line',
                            symbol: 'none',
                            color: '#E2242B',
                            data: this.notRunOil,
                            markPoint: {
                                data: this.markPointDataOil99,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil1,
                            type: 'line',
                            symbol: 'none',
                            color: '#8E388E',
                            data: this.oil1,
                            markPoint: {
                                data: this.markPointDataOil1,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil2,
                            type: 'line',
                            symbol: 'none',
                            color: '#FF4500',
                            data: this.oil2,
                            markPoint: {
                                data: this.markPointDataOil2,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil3,
                            type: 'line',
                            symbol: 'none',
                            color: '#2177C7',
                            data: this.oil3,
                            markPoint: {
                                data: this.markPointDataOil3,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil4,
                            type: 'line',
                            symbol: 'none',
                            color: '#B05432',
                            data: this.oil4,
                            markPoint: {
                                data: this.markPointDataOil4,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates
                        },
                        {
                            smooth: true,
                            name: reissue,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devReissue
                        },
                    ]
                };
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            _queryGeoSystemRecords: function() {
                var url = myUrls.queryGeoSystemRecords(),
                    me = this;
                utils.sendAjax(url, {}, function(resp) {
                    if (resp.status == 0) {
                        if (resp.categorys) {
                            me.filterOriginalData(resp.categorys);
                        }
                    }
                })
            },
            filterOriginalData: function(categorys) {
                var originalData = [];

                categorys.forEach(function(item) {
                    var treeItem = {
                        title: item.name,
                        categoryid: item.categoryid,
                        children: [],
                        checked: false,
                        expand: true,
                    };
                    item.records.forEach(function(record) {
                        if (record.useas == 1) {
                            record.title = record.name;
                            record.categoryid = item.categoryid;
                            treeItem.children.push(record);
                            record.checked = false;
                        }
                    });
                    if (treeItem.children.length) {
                        originalData.push(treeItem);
                    }

                });
                this.treeData = originalData;
            },
            onSelectStartUuid: function(startgeouuids) {
                this.startgeouuids = startgeouuids;
            },
            onSelectEndUuid: function(endgeouuids) {
                this.endgeouuids = endgeouuids;
            },
        },
        mounted: function() {
            var me = this;
            this.mapType = utils.getMapType();
            this.startgeouuids = [];
            this.endgeouuids = [];

            this.recvtime = [];
            this.veo = [];
            this.distance = [];
            this.totalad = [];
            this.notRunOil = [];
            this.markPointData = [];
            this.markPointDataOil1 = [];
            this.markPointDataOil2 = [];
            this.markPointDataOil3 = [];
            this.markPointDataOil4 = [];
            this.markPointDataOil99 = [];
            this.oil1 = [];
            this.oil2 = [];
            this.oil3 = [];
            this.oil4 = [];
            this.srcad0 = [];
            this.srcad1 = [];
            this.srcad2 = [];
            this.srcad3 = [];
            this.devStates = [];
            this.devReissue = [];

            var usoil2 = vRoot.$t('reportForm.oil2');
            var usoil3 = vRoot.$t('reportForm.oil3');
            var usoil4 = vRoot.$t('reportForm.oil4');
            if (isZh) {
                this.selectedLegend = {
                    '油液2': false,
                    '油液3': false,
                    '油液4': false,
                }
            } else {
                this.selectedLegend = {
                    'Tank2': false,
                    'Tank3': false,
                    'Tank4': false,
                }
            }





            setTimeout(function() {
                try {
                    me.chartsIns = echarts.init(document.getElementById('driving-charts'));
                    me.chartsIns.setOption(me.getChartsOption(), true);
                    me.chartsIns.on('legendselectchanged', function(param) {
                        me.selectedLegend = param.selected;
                    });
                } catch (e) {

                }
            }, 1000);

            this.initMap();
            this.queryDevicesTree();
            this._queryGeoSystemRecords();
        }
    })
}

function tripReport(groupslist) {
    vueInstanse = new Vue({
        el: "#trip-report",
        i18n: utils.getI18n(),
        data: {
            currentIndex: 1,
            loading: false,
            mapModal: false,
            mapType: null,
            groupslist: [],
            markerIns: null,
            isSpin: false,
            columns: [
                { title: vRoot.$t("reportForm.index"), type: 'index', width: 60 },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 80,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    editObject = params.row;
                                    vueInstanse.getDetailTableData(params.row);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.detailed") + "]")
                    }
                },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 150, sortable: true },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.tripCount"), key: 'tripcount', width: 100, sortable: true },
                { title: vRoot.$t("reportForm.duration") + '(H)', key: 'timeduration', width: 100, sortable: true },
                { title: vRoot.$t("reportForm.mileage") + '(Km)', key: 'totaldistanceduration', width: 110, sortable: true },
                { title: vRoot.$t("reportForm.oilConsumption") + '(L)', key: 'totalrunningfuel', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalotherfuel', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.startDate"), key: 'starttimeStr', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.endDate"), key: 'endtimeStr', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.minMileage"), key: 'starttotaldistance', width: 150, sortable: true },
                { title: vRoot.$t("reportForm.maxMileage"), key: 'endtotaldistance', width: 150, sortable: true },


            ],
            tableData: [],
            columnsDetails: [],
            tableDataDetails: [],
            treeData: [],
            tableHeight: 100,
            activeTab: 'tabTotal',
            tripSetting: null,
            tripSettingStr: vRoot.$t("reportForm.tripRule1"),
            tripSettingSrc: "images/tripin.png"
        },
        mixins: [treeMixin],
        methods: {
            exportData: function() {
                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.tripCount"),
                            vRoot.$t("reportForm.duration") + '(H)',
                            vRoot.$t("reportForm.mileage") + '(Km)',
                            vRoot.$t("reportForm.oilConsumption") + '(L)',
                            vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                            vRoot.$t("reportForm.startDate"),
                            vRoot.$t("reportForm.endDate"),
                            vRoot.$t("reportForm.minMileage"),
                            vRoot.$t("reportForm.maxMileage"),
                        ]
                    ];
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.tripcount);
                        itemArr.push(item.timeduration);
                        itemArr.push(item.totaldistanceduration);
                        itemArr.push(item.totalrunningfuel);
                        itemArr.push(item.totalotherfuel);
                        itemArr.push(item.starttimeStr);
                        itemArr.push(item.endtimeStr);
                        itemArr.push(item.starttotaldistance);
                        itemArr.push(item.endtotaldistance);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.tripReport'),
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                } else {

                    var columns = deepClone(this.columnsDetails);
                    columns.shift();
                    columns.unshift({ title: vRoot.$t("reportForm.index"), key: 'idx', width: 60 })

                    var data = [
                        []
                    ];
                    columns.forEach(function(item) {
                        data[0].push(item.title);
                    })

                    this.tableDataDetails.forEach(function(valitem) {
                        var arr = [];
                        columns.forEach(function(keyitem) {
                            arr.push(valitem[keyitem.key]);
                        })
                        data.push(arr);
                    })

                    var options = {
                        title: vRoot.$t('reportForm.tripReport') + ' - ' + editObject.deviceid,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();
                }



            },
            onClickDropdownMenu: function(cmd) {
                this.tripSetting = cmd;
                if (cmd == '0') {
                    this.tripSettingStr = vRoot.$t("reportForm.tripRule1");
                    this.tripSettingSrc = "images/tripin.png";
                } else if (cmd == '1') {
                    this.tripSettingStr = vRoot.$t("reportForm.tripRule2");
                    this.tripSettingSrc = "images/tripinout.png";
                } else if (cmd == '2') {
                    this.tripSettingStr = vRoot.$t("reportForm.tripRule3");
                    this.tripSettingSrc = "images/tripinoutin.png";
                }
            },
            getDetailTableData: function(row) {
                this.tableDataDetails = row.records;
                this.polygonLayer.clear();
                if (this.markerLayer != null) {
                    this.mapInstance.removeLayer(this.markerLayer);
                }
                if (this.tableDataDetails.length) {
                    var first = this.tableDataDetails[0];
                    first._highlight = true;
                    this.querySingleDevTracks(first);
                    if (this.tripSetting == '2') {
                        this.tableDataDetails.forEach(function(item) {
                            var points = item.points;
                            item.timeatshipto = Number(((points[2].updatetime - points[1].updatetime) / 1000 / 3600).toFixed(2));
                        })
                    }
                }
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 240;
            },
            verificationAddress: function(startgeouuids, endgeouuids) {
                var result = true;
                if (this.tripSetting == '0') {
                    if (startgeouuids.length == 0) {
                        result = false;
                    };
                } else {
                    if (startgeouuids.length == 0 || endgeouuids.length == 0) {
                        result = false;
                    };
                    startgeouuids.forEach(function(item) {
                        if (endgeouuids.indexOf(item) != -1) {
                            result = false;
                        }
                    });
                }

                return result;
            },
            querySingleDevTracks: function(row) {
                var me = this;
                var url = myUrls.queryTracks();
                var data = {
                    deviceid: row.deviceid,
                    begintime: row.starttimeStr,
                    endtime: row.endtimeStr,
                    timezone: timeDifference
                };
                me.extents = [];
                utils.sendAjax(url, data, function(resp) {
                    me.isSpin = false;
                    if (resp.status == 0) {
                        var records = resp.records;
                        if (records && records.length) {
                            utils.markersAndLineLayerToMap(me, records, true);
                            me.redrawCharts(records);
                            me.drawFence(row.points);
                            var polygon = new maptalks.Polygon(me.extents);
                            me.mapInstance.fitExtent(polygon.getExtent(), 0);
                        } else {
                            me.$Message.error(isZh ? '没有轨迹' : 'No Data');
                        }
                    }
                }, function() {
                    me.isSpin = false;
                });

            },
            onClickQuery: function() {
                var me = this;
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length) {
                    if (this.verificationAddress(this.startgeouuids, this.endgeouuids)) {
                        this.activeTab = 'tabTotal';
                        this.loading = true;
                        var url = myUrls.reportTrips();
                        var data = {
                            startday: this.dateVal[0],
                            endday: this.dateVal[1],
                            offset: timeDifference,
                            deviceids: deviceids,
                            triptype: Number(this.tripSetting),
                            startgeouuids: this.startgeouuids,
                            endgeouuids: this.endgeouuids,
                        };
                        utils.sendAjax(url, data, function(resp) {
                            me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                            me.loading = false;
                            if (resp.status == 0) {
                                var triptype = resp.triptype;
                                resp.summaries.forEach(function(item, i) {
                                    item.idx = i + 1;
                                    var deviceid = item.deviceid;
                                    var devicename = vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid;
                                    item.devicename = devicename;
                                    item.tripcount = item.records.length;
                                    item.starttimeStr = item.starttime > 0 ? DateFormat.longToLocalDateTimeStr(item.starttime) : 0;
                                    item.endtimeStr = item.endtime > 0 ? DateFormat.longToLocalDateTimeStr(item.endtime) : 0;
                                    item.timeduration = Number((item.timeduration / 1000 / 3600).toFixed(2));
                                    item.totaldistanceduration = Number((item.totaldistanceduration / 1000).toFixed(2));
                                    item.starttotaldistance = Number((item.starttotaldistance / 1000).toFixed(2));
                                    item.endtotaldistance = Number((item.endtotaldistance / 1000).toFixed(2));
                                    item.totalrunningfuel = item.totalrunningfuel / 100;
                                    item.totalotherfuel = item.totalotherfuel / 100;

                                    item.records.forEach(function(record, j) {
                                        var fenceName = '';
                                        record.idx = j + 1;
                                        record.deviceid = deviceid;
                                        record.devicename = devicename;
                                        record.starttimeStr = DateFormat.longToLocalDateTimeStr(record.starttime);
                                        record.endtimeStr = DateFormat.longToLocalDateTimeStr(record.endtime);
                                        record.timeduration = Number((record.timeduration / 1000 / 3600).toFixed(2));
                                        record.totaldistanceduration = Number((record.totaldistanceduration / 1000).toFixed(2));
                                        record.starttotaldistance = Number((record.starttotaldistance / 1000).toFixed(2));
                                        record.endtotaldistance = Number((record.endtotaldistance / 1000).toFixed(2));
                                        record.totalrunningfuel = record.totalrunningfuel / 100;
                                        record.totalotherfuel = record.totalotherfuel / 100;
                                        if (triptype == 0) {
                                            fenceName = record.points[0].geosystemrecord.name;
                                        } else if (triptype == 1) {
                                            fenceName = record.points[1].geosystemrecord.name + '→' + record.points[2].geosystemrecord.name;
                                        } else if (triptype == 2) {
                                            fenceName = record.points[1].geosystemrecord.name + '←→' + record.points[2].geosystemrecord.name;
                                        }
                                        record.fenceName = fenceName;
                                    })
                                })
                                me.tableData = resp.summaries;
                            };
                        }, function() {
                            me.loading = false;
                        })
                    } else {
                        me.$Message.error(isZh ? '请选择正确的出发区和收货区' : 'Please select the correct departure area and receiving area.');
                    }
                } else {
                    me.$Message.error(me.$t('reportForm.selectDevTip'));
                }

            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('trip-map');
                this.polygonLayer = new maptalks.VectorLayer('vector').addTo(this.mapInstance);
            },
            addFenceLabel: function(name, lon_lat) {
                new maptalks.Label(name, lon_lat, {
                    'textSymbol': {
                        'textFaceName': 'monospace',
                        'textFill': '#34495e',
                        'textHaloFill': '#fff',
                        'textHaloRadius': 4,
                        'textSize': 12,
                        'textWeight': 'bold',
                        'textVerticalAlignment': 'top'
                    }
                }).addTo(this.polygonLayer);
            },
            drawFence: function(points) {
                this.polygonLayer.clear();
                var me = this;
                var isBMap = utils.getMapType() == 'bMap';
                var symbol = {
                    'lineColor': '#e4393c',
                    'lineWidth': 2,
                    'polygonFill': 'rgb(135,196,240)',
                    'polygonOpacity': 0
                };
                var isDrawing = {};
                points.forEach(function(point) {

                    var element = point.geosystemrecord;
                    var georecorduuid = element.georecorduuid;
                    if (!isDrawing[georecorduuid]) {
                        switch (element.type) {
                            case 1:
                                if (isBMap) {
                                    var lon_lat = wgs84tobd09(element.lon1, element.lat1);
                                } else {
                                    var lon_lat = wgs84togcj02(element.lon1, element.lat1);
                                }

                                var point = {
                                    x: lon_lat[0],
                                    y: lon_lat[1]
                                }
                                var circle = new maptalks.Circle(point, element.radius1, {
                                    symbol: symbol
                                });
                                circle.addTo(me.polygonLayer);
                                var extent = circle.getExtent();
                                me.extents.push({
                                    x: extent.xmax,
                                    y: extent.ymax,
                                })
                                me.extents.push({
                                    x: extent.xmin,
                                    y: extent.ymin,
                                })
                                me.addFenceLabel(element.name, lon_lat);
                                break;
                            case 2:
                                var lon_lat_s = [];
                                if (isBMap) {
                                    var lon_lat = wgs84tobd09(element.lon1, element.lat1);
                                    lon_lat_s = wgs84sToBdPoints(JSON.parse(element.points2));
                                } else {
                                    var lon_lat = wgs84togcj02(element.lon1, element.lat1);
                                    lon_lat_s = wgs84sToGooglePoints(JSON.parse(element.points2));
                                }
                                var polygon = new maptalks.Polygon(lon_lat_s, {
                                    symbol: symbol
                                });
                                polygon.addTo(me.polygonLayer);
                                var extent = polygon.getExtent();
                                me.extents.push({
                                    x: extent.xmax,
                                    y: extent.ymax,
                                })
                                me.extents.push({
                                    x: extent.xmin,
                                    y: extent.ymin,
                                })
                                me.addFenceLabel(element.name, lon_lat);
                                break;
                        }
                        isDrawing[georecorduuid] = true;

                    }

                });

            },
            redrawCharts: function(tracks) {
                var me = this;
                var records = tracks;
                var distance = []; //总里程;
                var recvtime = []; //时间
                var veo = []; //速度
                var totalad = [];
                var notRunOil = [];
                var oil1 = [];
                var oil2 = [];
                var oil3 = [];
                var oil4 = [];
                var devStates = [];
                var devReissue = [];
                this.disMin = 0;
                var totalDistanceMin = 0;
                records.forEach(function(item, index) {
                    item.totaldistance = item.totaldistance / 1000;
                    if (index == 0) {
                        totalDistanceMin = item.totaldistance;
                        firstDistance = totalDistanceMin;
                    }

                    oil1.push(item.ad0 / 100);
                    oil2.push(item.ad1 / 100);
                    oil3.push(item.ad2 / 100);
                    oil4.push(item.ad3 / 100);
                    devStates.push(item.strstatus);
                    devReissue.push(item.reissue == 0 ? me.$t('header.no') : me.$t('header.yes'));
                    totalad.push(item.totalad / 100);
                    notRunOil.push(item.totalnotrunningad / 100);
                    recvtime.push(DateFormat.longToLocalDateTimeStr(item.updatetime));
                    veo.push(Number((item.speed / 1000).toFixed(2)));
                    distance.push(Number((item.totaldistance - totalDistanceMin).toFixed(3)));
                });



                this.distance = distance;
                this.recvtime = recvtime;
                this.veo = veo;
                this.totalad = totalad;
                this.notRunOil = notRunOil;
                this.oil1 = oil1;
                this.oil2 = oil2;
                this.oil3 = oil3;
                this.oil4 = oil4;
                this.devStates = devStates;
                this.devReissue = devReissue;

                this.chartsIns.setOption(this.getChartsOption());
            },
            getChartsOption: function() {

                var totoil = vRoot.$t('reportForm.totalOil');
                var notRunTotalad = vRoot.$t('reportForm.notRunTotalad');
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');
                var status = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t('reportForm.reissue');

                return {
                    grid: {
                        top: 40,
                        left: 60,
                        right: 60,
                        bottom: 20,
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName && v[i].seriesName != time) {
                                    if (v[i].seriesName == dis) {
                                        var currentDistance = v[i].value;
                                        var totalDistance = ((Number(currentDistance) + firstDistance / 1000)).toFixed(2);
                                        data += v[i].seriesName + ' : ' + currentDistance + "km(T:" + totalDistance + 'km)<br/>';

                                    } else if (v[i].seriesName == notRunTotalad || v[i].seriesName == totoil || v[i].seriesName == usoil1 || v[i].seriesName == usoil2 || v[i].seriesName == usoil3 || v[i].seriesName == usoil4) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'L<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else {
                                        data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, totoil, notRunTotalad, usoil1, usoil2, usoil3, usoil4],
                        selected: this.selectedLegend,
                        x: 'left',
                    },

                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: speed,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: dis, //
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.veo
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distance
                        }, {
                            smooth: true,
                            name: totoil,
                            type: 'line',
                            symbol: 'none',
                            color: '#C1232B',
                            data: this.totalad,
                            markPoint: {
                                data: this.markPointData,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: notRunTotalad,
                            type: 'line',
                            symbol: 'none',
                            color: '#E2242B',
                            data: this.notRunOil,
                            markPoint: {
                                data: this.markPointDataOil99,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil1,
                            type: 'line',
                            symbol: 'none',
                            color: '#8E388E',
                            data: this.oil1,
                            markPoint: {
                                data: this.markPointDataOil1,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil2,
                            type: 'line',
                            symbol: 'none',
                            color: '#FF4500',
                            data: this.oil2,
                            markPoint: {
                                data: this.markPointDataOil2,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil3,
                            type: 'line',
                            symbol: 'none',
                            color: '#2177C7',
                            data: this.oil3,
                            markPoint: {
                                data: this.markPointDataOil3,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil4,
                            type: 'line',
                            symbol: 'none',
                            color: '#B05432',
                            data: this.oil4,
                            markPoint: {
                                data: this.markPointDataOil4,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates
                        },
                        {
                            smooth: true,
                            name: reissue,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devReissue
                        },
                    ]
                };
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            _queryGeoSystemRecords: function() {
                var url = myUrls.queryGeoSystemRecords(),
                    me = this;
                utils.sendAjax(url, {}, function(resp) {
                    if (resp.status == 0) {
                        if (resp.categorys) {
                            me.filterOriginalData(resp.categorys);
                        }
                    }
                })
            },
            filterOriginalData: function(categorys) {
                var originalData = [];

                categorys.forEach(function(item) {
                    var treeItem = {
                        title: item.name,
                        categoryid: item.categoryid,
                        children: [],
                        checked: false,
                        expand: true,
                    };
                    item.records.forEach(function(record) {
                        if (record.useas == 1) {
                            record.title = record.name;
                            record.categoryid = item.categoryid;
                            treeItem.children.push(record);
                            record.checked = false;
                        }
                    });
                    if (treeItem.children.length) {
                        originalData.push(treeItem);
                    }

                });
                this.treeData = originalData;
            },
            onSelectStartUuid: function(startgeouuids) {
                this.startgeouuids = startgeouuids;
            },
            onSelectEndUuid: function(endgeouuids) {
                this.endgeouuids = endgeouuids;
            },
        },
        watch: {
            tripSetting: function(type) {
                var columnsDetails = [
                    { title: vRoot.$t("reportForm.index"), type: 'index', width: 60 },
                    { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 150, sortable: true },
                    { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 150, sortable: true },
                    { title: isZh ? '围栏' : 'fence', key: 'fenceName', width: 150, sortable: true },
                    { title: vRoot.$t("reportForm.duration") + '(H)', key: 'timeduration', width: 100, sortable: true },
                    { title: vRoot.$t("reportForm.mileage") + '(Km)', key: 'totaldistanceduration', width: 110, sortable: true },
                    { title: vRoot.$t("reportForm.oilConsumption") + '(L)', key: 'totalrunningfuel', width: 150, sortable: true },
                    { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalotherfuel', width: 150, sortable: true },
                    { title: vRoot.$t("reportForm.startDate"), key: 'starttimeStr', width: 150, sortable: true },
                    { title: vRoot.$t("reportForm.endDate"), key: 'endtimeStr', width: 150, sortable: true },
                    { title: vRoot.$t("reportForm.minMileage"), key: 'starttotaldistance', width: 150, sortable: true },
                    { title: vRoot.$t("reportForm.maxMileage"), key: 'endtotaldistance', width: 150, sortable: true },

                ];
                if (type == '2') {
                    columnsDetails = [
                        { title: vRoot.$t("reportForm.index"), type: 'index', width: 60 },
                        { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 150, sortable: true },
                        { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 150, sortable: true },
                        { title: isZh ? '围栏' : 'fence', key: 'fenceName', width: 150, sortable: true },
                        { title: vRoot.$t("reportForm.duration") + '(H)', key: 'timeduration', width: 100, sortable: true },
                        { title: vRoot.$t("reportForm.mileage") + '(Km)', key: 'totaldistanceduration', width: 110, sortable: true },
                        { title: vRoot.$t("reportForm.oilConsumption") + '(L)', key: 'totalrunningfuel', width: 150, sortable: true },
                        { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalotherfuel', width: 150, sortable: true },
                        { title: isZh ? '在收货方时长(H)' : "Time at ship to(H)", key: 'timeatshipto', width: 180, sortable: true },
                        { title: vRoot.$t("reportForm.startDate"), key: 'starttimeStr', width: 150, sortable: true },
                        { title: vRoot.$t("reportForm.endDate"), key: 'endtimeStr', width: 150, sortable: true },
                        { title: vRoot.$t("reportForm.minMileage"), key: 'starttotaldistance', width: 150, sortable: true },
                        { title: vRoot.$t("reportForm.maxMileage"), key: 'endtotaldistance', width: 150, sortable: true },
                    ];
                }
                this.columnsDetails = columnsDetails;
            }
        },
        mounted: function() {
            var me = this;
            this.mapType = utils.getMapType();
            this.tripSetting = '0';
            this.startgeouuids = [];
            this.endgeouuids = [];

            this.recvtime = [];
            this.veo = [];
            this.distance = [];
            this.totalad = [];
            this.notRunOil = [];
            this.markPointData = [];
            this.markPointDataOil1 = [];
            this.markPointDataOil2 = [];
            this.markPointDataOil3 = [];
            this.markPointDataOil4 = [];
            this.markPointDataOil99 = [];
            this.oil1 = [];
            this.oil2 = [];
            this.oil3 = [];
            this.oil4 = [];
            this.srcad0 = [];
            this.srcad1 = [];
            this.srcad2 = [];
            this.srcad3 = [];
            this.devStates = [];
            this.devReissue = [];

            var usoil2 = vRoot.$t('reportForm.oil2');
            var usoil3 = vRoot.$t('reportForm.oil3');
            var usoil4 = vRoot.$t('reportForm.oil4');

            if (isZh) {
                this.selectedLegend = {
                    '油液2': false,
                    '油液3': false,
                    '油液4': false,
                }
            } else {
                this.selectedLegend = {
                    'Tank2': false,
                    'Tank3': false,
                    'Tank4': false,
                }
            }



            setTimeout(function() {
                me.chartsIns = echarts.init(document.getElementById('leak-charts'));
                me.chartsIns.setOption(me.getChartsOption(), true);
                me.chartsIns.on('legendselectchanged', function(param) {
                    me.selectedLegend = param.selected;
                });
            }, 1000);

            this.initMap();
            this.queryDevicesTree();
            this._queryGeoSystemRecords();
        }
    })
}


function workingHoursReport() {
    vueInstanse = new Vue({
        el: "#working-hours-report",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            isSpin: false,
            tank: '0',
            startDate: DateFormat.longToDateStr(Date.now(), timeDifference),
            startTime: '00:00:00',
            endDate: DateFormat.longToDateStr(Date.now(), timeDifference),
            endTime: '23:59:59',
            options: {
                disabledDate: function(date) {
                    return date && date.valueOf() > Date.now();
                }
            },
            dateTimeRangeVal: [DateFormat.longToDateStr(Date.now(), timeDifference) + " 00:00:00", DateFormat.longToDateStr(Date.now(), timeDifference) + " 23:59:59"],
            groupslist: [],
            columns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 65,
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                },
                {
                    title: vRoot.$t('reportForm.mileage') + '(km)',
                    key: 'totaldistance',
                },
                {
                    title: vRoot.$t("reportForm.workingHours") + '(H)',
                    key: 'totalacc',

                },

                {
                    title: vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                    key: 'averagespeed',
                },

            ],
            tableData: [],
            oil: [],
            recvtime: [],
            chartDataList: [],
        },
        mixins: [treeMixin],
        methods: {
            onTimeRangeChange: function(timeRange) {
                this.dateTimeRangeVal = timeRange;
            },
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t('reportForm.mileage') + '(km)',
                        vRoot.$t("reportForm.workingHours") + '(H)',
                        vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.totalacc);
                    itemArr.push(item.averagespeed);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.workingHoursReport'),
                    data: data,
                    dateRange: this.begintimeAndEndtime,
                }
                new XlsxCls(options).exportExcel();
            },
            getChartsOption: function(deviceNames, oils, disArr, hours) {

                var dis = vRoot.$t('reportForm.mileage');
                var workingHours = vRoot.$t("reportForm.workingHours") + '(H)';

                return {
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v, a) {
                            var data = v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName == dis) {
                                    data += v[i].seriesName + ' : ' + v[i].value + 'km<br/>';
                                } else if (v[i].seriesName == workingHours) {
                                    data += v[i].seriesName + ' : ' + utils.timeStamp(v[i].value * 1000 * 3600) + '<br/>';
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [dis, workingHours],
                        y: 13,
                        x: 'center'
                    },

                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        //boundaryGap : false,
                        axisLabel: {
                            show: true,
                            interval: 0, // {number}
                            rotate: 0,
                            margin: 8,
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        data: deviceNames
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }],
                    series: [{
                            name: dis,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                                //悬浮式样式
                            },
                            data: disArr
                        },
                        {
                            name: workingHours,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                            },
                            data: hours
                        },
                    ]
                };

            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 365;
            },
            onClickQuery: function() {
                var self = this;
                this.activeTab = 'tabTotal';
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }


                var begintime = DateFormat.longToDateStr(this.startDate.getTime(), timeDifference) + ' ' + this.startTime;
                var endtime = DateFormat.longToDateStr(this.endDate.getTime(), timeDifference) + ' ' + this.endTime;

                if (new Date(begintime).getTime() > new Date(endtime).getTime()) {
                    this.$Message.error(this.$t('videoback.downloadTips3'));
                    return;
                }

                this.begintimeAndEndtime = begintime + '-' + endtime;

                this.tableData = [];
                this.chartDataList = [];
                var data = {
                    // username: vstore.state.userName,
                    begintime: begintime,
                    endtime: endtime,
                    timezone: timeDifference,
                    devices: deviceids,
                    oilindex: 0
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportOilManHour(), data, function(resp) {
                    self.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {
                            var chartDataList = [];

                            // render: function(h, pramas) {
                            //     var row = pramas.row; totaldistance
                            //     return h('sapn', {}, (row.totaldistance / 1000).toFixed(2));
                            // },
                            // render: function(h, pramas) {
                            //     var row = pramas.row; totaloil
                            //     return h('sapn', {}, (row.totaloil / 100).toFixed(2));
                            // },

                            // render: function(h, pramas) {
                            //     var row = pramas.row;  totalacc
                            //     return h('sapn', {}, utils.timeStamp(row.totalacc));
                            // },

                            resp.records.forEach(function(item, index) {

                                item.index = index + 1;
                                item.devicename = vstore.state.deviceInfos[item.deviceid] ? vstore.state.deviceInfos[item.deviceid].devicename : item.deviceid;
                                if (index % 4 == 0) {
                                    chartDataList.push({
                                        data: [],
                                        oil: [],
                                        dis: [],
                                        hours: [],
                                    })
                                }
                                var len = chartDataList.length - 1;
                                var totalacc = (item.totalacc / 1000 / 3600).toFixed(2);
                                item.idleoil = item.idleoil / 100;
                                item.runoilper100km = item.runoilper100km;
                                item.totaldistance = (item.totaldistance / 1000).toFixed(2)
                                item.totalacc = totalacc
                                item.totaloil = item.totaloil / 100;
                                item.totalnotrunningad = item.totalnotrunningad / 100;
                                item.addnotrunningad = item.addnotrunningad / 100;
                                item.leaknotrunningad = item.leaknotrunningad / 100;

                                chartDataList[len].data.push(item.devicename);
                                chartDataList[len].oil.push(item.totaloil);
                                chartDataList[len].dis.push(Number(item.totaldistance));
                                chartDataList[len].hours.push(Number(totalacc));

                                if (item.totaldistance == 0 || totalacc == 0) {
                                    item.averagespeed = 0
                                } else {
                                    item.averagespeed = (Number(item.totaldistance) / Number(totalacc)).toFixed(2);
                                }


                            });

                            self.tableData = resp.records;
                            self.chartDataList = chartDataList;


                            setTimeout(function() {
                                self.initCharts();
                            }, 300);
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            initCharts: function() {
                var index = 0;
                var len = this.chartDataList.length;
                while (index < len) {
                    var chartsIns = echarts.init(document.getElementById('charts' + index));
                    var data = this.chartDataList[index]
                    chartsIns.setOption(this.getChartsOption(data.data, data.oil, data.dis, data.hours), true);

                    // chartDataList[len].data.push(item.devicename);
                    // chartDataList[len].oil.push(item.totaloil);
                    // chartDataList[len].dis.push(item.totaldistance);
                    // chartDataList[len].hours.push(item.totalacc);

                    index++;
                }
            }
        },
        mounted: function() {
            this.myChart = null;
            this.records = [];
            this.queryDevicesTree();
        }
    });
}

function oilDayDetail(groupslist) {
    vueInstanse = new Vue({
        el: '#oil-day-details',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            date: new Date(Date.now() - 60 * 60 * 24 * 1000),
            lastTableHeight: 100,
            groupslist: [],
            columns: [{
                    title: vRoot.$t("reportForm.time"),
                    key: 'statisticsday',
                    width: 105,
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                    width: 125,
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                    width: 125,
                },
                {
                    title: vRoot.$t('reportForm.mileage') + '(km)',
                    key: 'totaldistance',
                    width: 110,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.oilConsumption") + '(L)',
                    key: 'totaloil',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.fuelVolume") + '(L)',
                    key: 'addoil',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.oilLeakage") + '(L)',
                    key: 'leakoil',
                    width: 130,
                    sortable: true,
                },
                { title: vRoot.$t('reportForm.idleoil') + '(L)', key: 'idleoil', width: 120, sortable: true, },

                {
                    title: vRoot.$t("reportForm.workingHours") + '(H)',
                    key: 'totalacc',
                    width: 140,
                    sortable: true,

                },
                { title: vRoot.$t('reportForm.runoilper100km') + '(L)', key: 'runoilper100km', width: 160, sortable: true, },
                {
                    title: vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                    key: 'oilper100km',
                    width: 160,
                    sortable: true,
                },
                {
                    title: vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                    key: 'oilperhour',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                    key: 'averagespeed',
                    width: 150,
                    sortable: true,
                },
                { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalnotrunningad', sortable: true, width: 145, },
                { title: vRoot.$t("reportForm.addnotrunningad") + '(L)', key: 'addnotrunningad', sortable: true, width: 155, },
                { title: vRoot.$t("reportForm.leaknotrunningad") + '(L)', key: 'leaknotrunningad', sortable: true, width: 155, },

            ],
            tableData: [],
            currentIndex: 1,
            dateOptions: {
                disabledDate: function(date) {
                    return (date && date.valueOf()) > Date.now();
                }
            },
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.time"),
                        vRoot.$t('reportForm.mileage') + '(km)',
                        vRoot.$t("reportForm.oilConsumption") + '(L)',
                        vRoot.$t("reportForm.fuelVolume") + '(L)',
                        vRoot.$t("reportForm.oilLeakage") + '(L)',
                        vRoot.$t('reportForm.idleoil') + '(L)',
                        vRoot.$t("reportForm.workingHours") + '(H)',
                        vRoot.$t('reportForm.runoilper100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                        vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                        vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                        vRoot.$t("reportForm.addnotrunningad") + '(L)',
                        vRoot.$t("reportForm.leaknotrunningad") + '(L)',
                    ]
                ];
                this.records.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.statisticsday);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.totaloil);
                    itemArr.push(item.addoil);
                    itemArr.push(item.leakoil);
                    itemArr.push(item.idleoil);
                    itemArr.push(item.totalacc);
                    itemArr.push(item.runoilper100km);
                    itemArr.push(item.oilper100km);
                    itemArr.push(item.oilperhour);
                    itemArr.push(item.averagespeed);
                    itemArr.push(item.totalnotrunningad);
                    itemArr.push(item.addnotrunningad);
                    itemArr.push(item.leaknotrunningad);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.oilDayDetail'),
                    data: data,
                    dateRange: false,
                }
                new XlsxCls(options).exportExcel();

            },
            nextDay: function() {
                this.date = new Date(this.date.getTime() + 60 * 60 * 24 * 1000);
            },
            prevDay: function() {
                this.date = new Date(this.date.getTime() - 60 * 60 * 24 * 1000);
            },
            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 175;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportOilDaily();
                    var startday = DateFormat.format(this.date, 'yyyy-MM-dd');
                    var data = {
                        startday: startday,
                        endday: startday,
                        offset: timeDifference,
                        devices: deviceids,
                    };
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        if (resp.status === 0) {

                            var tableData = [];
                            var records = resp.records;
                            records.forEach(function(device) {
                                var deviceid = device.deviceid;
                                device.records.forEach(function(item) {
                                    item.deviceid = deviceid;
                                    item.devicename = vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid;
                                    var totalacc = (item.totalacc / 1000 / 3600).toFixed(2);
                                    item.idleoil = item.idleoil / 100;
                                    item.runoilper100km = item.runoilper100km;
                                    item.totaldistance = (item.totaldistance / 1000).toFixed(2)
                                    item.totalacc = totalacc;
                                    item.totaloil = item.totaloil / 100;
                                    item.addoil = item.addoil / 100;
                                    item.leakoil = item.leakoil / 100;
                                    item.totalnotrunningad = item.totalnotrunningad / 100;
                                    item.addnotrunningad = item.addnotrunningad / 100;
                                    item.leaknotrunningad = item.leaknotrunningad / 100;

                                    if (item.totaldistance == 0 || item.totalacc == 0) {
                                        item.averagespeed = 0
                                    } else {
                                        item.averagespeed = (Number(item.totaldistance) / Number(totalacc)).toFixed(2);
                                    }
                                    tableData.push(item);
                                })

                            })

                            me.records = tableData;
                            me.tableData = me.records.slice(0, 20);
                            me.total = me.records.length;

                            me.currentIndex = 1;
                        } else {
                            me.tableData = [];
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            me.records = [];
            me.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


function addLeakMonthDetail(groupslist) {
    vueInstanse = new Vue({
        el: '#add-leak-month-detail',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            isSpin: false,
            tableHeight: 100,
            groupslist: [],
            month: '',
            tank: '0',
            oilIndexLabel: oilIndexLabel,
            columns: [{
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                    width: 180,
                },
                {
                    title: vRoot.$t("reportForm.time"),
                    key: 'statisticsday',
                    width: 300,
                },
                {
                    title: isZh ? '油路' : 'Box Index',
                    key: 'oilindexStr',
                    width: 120,
                }, {
                    title: (isZh ? '状态' : 'Status'),
                    key: 'oilStatus',
                    width: 120,
                }, {
                    title: (isZh ? '油量' : 'Fuel Volume') + '(L)',
                    key: 'oilVolume',
                    width: 120,
                }, {
                    title: (isZh ? '开始油量' : 'Start Fuel Volume') + '(L)',
                    key: 'soil',
                    width: 120,
                }, {
                    title: (isZh ? '结束油量' : 'End Fuel Volume') + '(L)',
                    key: 'eoil',
                    width: 120,
                },
                {
                    title: (isZh ? '地址' : 'Address'),
                    key: 'address',
                    width: 500,
                },
            ],
            tableData: [],
            dateOptions: {
                disabledDate: function(date) {
                    return (date && date.valueOf()) > Date.now();
                }
            },
        },
        methods: {
            exportData: function() {


                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.time"),
                        isZh ? '油路' : 'Box Index',
                        isZh ? '状态' : 'Status',
                        (isZh ? '油量' : 'Fuel Volume') + '(L)',
                        (isZh ? '开始油量' : 'Start Fuel Volume') + '(L)',
                        (isZh ? '结束油量' : 'End Fuel Volume') + '(L)',
                        (isZh ? '地址' : 'Address'),
                    ]
                ];
                var len = this.tableData.length - 1;
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    if (len == index) {
                        itemArr.push(isZh ? '总计' : 'Total');
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push(item.statisticsday);
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push('');
                        itemArr.push('');
                    } else {
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.statisticsday);
                        itemArr.push(item.oilindexStr);
                        itemArr.push(item.oilStatus);
                        itemArr.push(item.oilVolume);
                        itemArr.push(item.soil);
                        itemArr.push(item.eoil);
                        itemArr.push(item.address);
                    }

                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.addLeakMonthDetail') + this.queryDeviceId,
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 530;
            },
            onClickQuery: function() {
                var me = this;
                if (!this.queryDeviceId) {
                    this.$Message.error(me.$t("reportForm.selectDevTip"));
                    return;
                };

                var url = myUrls.reportOilRecordMonth();
                var yearmonth = DateFormat.format(this.month, 'yyyy-MM');
                var yearmonthArr = yearmonth.split("-");
                var data = {
                    year: Number(yearmonthArr[0]),
                    month: Number(yearmonthArr[1]),
                    offset: timeDifference,
                    deviceids: [this.queryDeviceId],
                    oilindex: Number(this.tank),
                    oilstate: 99,
                }
                utils.sendAjax(url, data, function(resp) {

                    if (resp.status == 0) {
                        if (resp.records) {
                            var oilArr = [];
                            var points = [];
                            var increaseOil = 0;
                            var reduceOil = 0;
                            resp.records.forEach(function(item) {
                                var index = 1;
                                var deviceid = item.deviceid;
                                item.records.forEach(function(record) {
                                    var oilstate = record.oilstate;
                                    if (oilstate == -1 || oilstate == 1) {
                                        var oilStatus = '';
                                        record.eoil = record.eoil / 100;
                                        record.soil = record.soil / 100;
                                        var oil = Math.abs(record.eoil - record.soil);
                                        switch (oilstate) {
                                            case -1:
                                                reduceOil += oil;
                                                oilStatus = isZh ? '漏油' : 'Leak';
                                                break;
                                            case 1:
                                                increaseOil += oil
                                                oilStatus = isZh ? '加油' : 'Refuel';
                                                break;
                                        }
                                        var oilindex = record.oilindex;
                                        var oilindexStr = '';
                                        switch (oilindex) {
                                            case 0:
                                                oilindexStr = isZh ? '总行驶' : 'Total Driving';
                                                break;
                                            case 1:
                                                oilindexStr = isZh ? '油路1' : 'Tank1';
                                                break;
                                            case 2:
                                                oilindexStr = isZh ? '油路2' : 'Tank2';
                                                break;
                                            case 3:
                                                oilindexStr = isZh ? '油路3' : 'Tank3';
                                                break;
                                            case 4:
                                                oilindexStr = isZh ? '油路4' : 'Tank4';
                                                break;
                                            case 99:
                                                oilindexStr = isZh ? '总非行驶' : 'Total Not Run';
                                                break;

                                            default:
                                                break;
                                        };
                                        var callat = Number(record.slat.toFixed(5));
                                        var callon = Number(record.slon.toFixed(5));
                                        var address = LocalCacheMgr.getAddress(callon, callat);
                                        if (!address) {
                                            address = '';
                                            points.push({
                                                lat: callat,
                                                lon: callon,
                                            })
                                        }
                                        oilArr.push({
                                            index: index,
                                            deviceid: deviceid,
                                            devicename: vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid,
                                            oilindex: record.oilindex,
                                            oilindexStr: oilindexStr,
                                            oilrecordid: record.oilrecordid,
                                            oilVolume: oil.toFixed(2),
                                            soil: record.soil.toFixed(2),
                                            eoil: record.eoil.toFixed(2),
                                            begintime: record.begintime,
                                            endtime: record.endtime,
                                            marker: record.marker,
                                            oilStatus: oilStatus,
                                            statisticsday: DateFormat.longToLocalDateTimeStr(record.begintime) + ' - ' + DateFormat.longToLocalDateTimeStr(record.endtime),
                                            oilrecords: [record],
                                            callat: callat,
                                            callon: callon,
                                            address: address
                                        })
                                        index++;
                                    }

                                });
                            });

                            oilArr.sort(function(a, b) {
                                return b.endtime - a.endtime;
                            });

                            var unionPoints = utils.unionLonLat(points);
                            var url = myUrls.poiBatch();
                            utils.sendAjax(url, {
                                points: unionPoints
                            }, function(respData) {
                                if (respData.status == 0) {
                                    var addresspoints = respData.points;
                                    addresspoints.forEach(function(point) {
                                        var lon = point.lon;
                                        var lat = point.lat;
                                        LocalCacheMgr.setAddress(point.lon, point.lat, point.address);

                                        oilArr.forEach(function(item) {
                                            if (item.callon == lon && item.callat == lat) {
                                                item.address = point.address
                                            }
                                        });
                                    });
                                }
                                me.tableData = oilArr;

                                if (oilArr.length) {
                                    var first = oilArr[0];
                                    first._highlight = true;
                                    me.queryTracks(first);
                                }

                                if (isZh) {
                                    me.tableData.push({
                                        statisticsday: '总加油量 : ' + increaseOil.toFixed(2) + 'L , ' + '总漏油量 : ' + reduceOil.toFixed(2) + 'L '
                                    })

                                } else {
                                    me.tableData.push({
                                        statisticsday: 'Total fuel consumption : ' + increaseOil.toFixed(2) + 'L , ' + 'Total oil leakage : ' + reduceOil.toFixed(2) + 'L'
                                    });
                                }
                            }, function() {
                                me.tableData = oilArr;
                                if (isZh) {
                                    me.tableData.push({
                                        statisticsday: '总加油量 : ' + increaseOil.toFixed(2) + 'L , ' + '总漏油量 : ' + reduceOil.toFixed(2) + 'L '
                                    })

                                } else {
                                    me.tableData.push({
                                        statisticsday: 'Total fuel consumption : ' + increaseOil.toFixed(2) + 'L , ' + 'Total oil leakage : ' + reduceOil.toFixed(2) + 'L'
                                    });
                                }
                            });


                        } else {
                            me.$Message.error(self.$t("reportForm.noRecord"));
                        }

                    } else {
                        me.$Message.error(resp.cause);
                    }
                });
            },

            queryTracks: function(row) {
                console.log('queryTracks', row);
                if (!row.deviceid) {
                    return;
                };
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: DateFormat.longToLocalDateTimeStr(row.begintime - 60 * 10 * 1000),
                        endtime: DateFormat.longToLocalDateTimeStr(row.endtime + 60 * 10 * 1000),
                        timezone: timeDifference
                    };
                me.oilTracks = [];
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.markersAndLineLayerToMap(records, row);
                            me.redrawCharts(records);
                            me.oilTracks = records;
                        } else {

                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            markersAndLineLayerToMap: function(tracks, row) {
                var begintime = row.begintime;
                var endtime = row.endtime;
                var oilrecords = row.oilrecords;

                var vueInstanse = this;
                if (vueInstanse.markerLayer != null) {
                    vueInstanse.mapIns.removeLayer(vueInstanse.markerLayer);
                }
                var isBMap = utils.getMapType();
                var points = [];
                var firstPoints = [];
                var addLeakPoints = [];
                var lastPoints = [];
                tracks.forEach(function(track, index) {
                    track.idx = index;
                    track.totaldistance = track.totaldistance / 1000;
                    track.totalad = track.totalad / 100;
                    track.ad0 = track.ad0 / 100;
                    track.ad1 = track.ad1 / 100;
                    track.ad2 = track.ad2 / 100;
                    track.ad3 = track.ad3 / 100;
                    track.totalnotrunningad = track.totalnotrunningad / 100;
                    if (isBMap) {
                        var g_lon_lat = wgs84tobd09(track.callon, track.callat);
                        track.point = {
                            y: g_lon_lat[1],
                            x: g_lon_lat[0]
                        };
                    } else {
                        var lng_lat = wgs84togcj02(track.callon, track.callat);
                        track.point = {
                            y: lng_lat[1],
                            x: lng_lat[0]
                        };
                    }
                    if (track.updatetime < begintime) {
                        firstPoints.push(track.point);
                    } else if (begintime <= track.updatetime && track.updatetime <= endtime) {
                        addLeakPoints.push(track.point);
                    } else if (track.updatetime > endtime) {
                        lastPoints.push(track.point);
                    }
                    points.push(track.point);
                })
                if (firstPoints.length) {
                    addLeakPoints.unshift(firstPoints[firstPoints.length - 1])
                }
                if (lastPoints.length) {
                    addLeakPoints.push(lastPoints[0]);
                }
                var sTrack = tracks[0];

                var smarker = new maptalks.Marker(
                    [sTrack.point.x, sTrack.point.y], {
                        symbol: {
                            'markerFile': './images/icon_st.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': 0,
                            'markerDy': 0,
                            'markerDx': 0,
                        },
                        zIndex: 999
                    }
                );

                var eTrack = tracks[tracks.length - 1];
                var emarker = new maptalks.Marker(
                    [eTrack.point.x, eTrack.point.y], {
                        symbol: {
                            'markerFile': './images/icon_en.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': 0,
                            'markerDy': 0,
                            'markerDx': 0,
                        },
                        zIndex: 999
                    }
                );

                var firstLineString = new maptalks.LineString(
                    firstPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'red'],
                                    [1.00, 'red']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })
                var centerLineString = new maptalks.LineString(
                    addLeakPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'green'],
                                    [1.00, 'green']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })

                var carTrackIndex = utils.getCalMarkPointIndex(tracks, row);
                var carTrack = tracks[carTrackIndex];

                this.carMarker = new maptalks.Marker(
                    [carTrack.point.x, carTrack.point.y], {
                        symbol: this.getMarkerSymbol(carIconTypes[this.queryDeviceId], carTrack.course)
                    }
                );

                var lastLineString = new maptalks.LineString(
                    lastPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'red'],
                                    [1.00, 'red']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })


                vueInstanse.markerLayer = new maptalks.VectorLayer('marker', [smarker, emarker, firstLineString, lastLineString, centerLineString, this.carMarker]);
                vueInstanse.markerLayer.addTo(vueInstanse.mapIns);



                var polygon = new maptalks.Polygon(points);
                this.mapIns.fitExtent(polygon.getExtent(), 0);

                this.markPointData = utils.calMarkPoint(tracks, oilrecords, 0);
                this.markPointDataOil1 = utils.calMarkPoint(tracks, oilrecords, 1);
                this.markPointDataOil2 = utils.calMarkPoint(tracks, oilrecords, 2);
                this.markPointDataOil3 = utils.calMarkPoint(tracks, oilrecords, 3);
                this.markPointDataOil4 = utils.calMarkPoint(tracks, oilrecords, 4);
                this.markPointDataOil99 = utils.calMarkPoint(tracks, oilrecords, 99);


            },
            redrawCharts: function(tracks) {
                var me = this;
                var records = tracks;
                var distance = []; //总里程;
                var recvtime = []; //时间
                var veo = []; //速度
                var totalad = [];
                var notRunOil = [];
                var oil1 = [];
                var oil2 = [];
                var oil3 = [];
                var oil4 = [];
                var devStates = [];
                var devReissue = [];
                this.disMin = 0;
                var totalDistanceMin = 0;
                records.forEach(function(item, index) {

                    if (index == 0) {
                        totalDistanceMin = item.totaldistance;
                        firstDistance = totalDistanceMin;
                    }

                    oil1.push(item.ad0);
                    oil2.push(item.ad1);
                    oil3.push(item.ad2);
                    oil4.push(item.ad3);
                    devStates.push(item.strstatus);
                    devReissue.push(item.reissue == 0 ? me.$t('header.no') : me.$t('header.yes'));
                    totalad.push(item.totalad);
                    notRunOil.push(item.totalnotrunningad);
                    recvtime.push(DateFormat.longToLocalDateTimeStr(item.updatetime));
                    veo.push(Number((item.speed / 1000).toFixed(2)));
                    distance.push(Number((item.totaldistance - totalDistanceMin).toFixed(3)));
                });



                this.distance = distance;
                this.recvtime = recvtime;
                this.veo = veo;
                this.totalad = totalad;
                this.notRunOil = notRunOil;
                this.oil1 = oil1;
                this.oil2 = oil2;
                this.oil3 = oil3;
                this.oil4 = oil4;
                this.devStates = devStates;
                this.devReissue = devReissue;

                this.chartsIns.setOption(this.getChartsOption());
            },
            getChartsOption: function() {

                var totoil = vRoot.$t('reportForm.totalOil');
                var notRunTotalad = vRoot.$t('reportForm.notRunTotalad');
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');
                var status = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t('reportForm.reissue');

                return {
                    grid: {
                        top: 40,
                        left: 60,
                        right: 60,
                        bottom: 20,
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName && v[i].seriesName != time) {
                                    if (v[i].seriesName == dis) {
                                        var currentDistance = v[i].value;
                                        var totalDistance = ((Number(currentDistance) + firstDistance / 1000)).toFixed(2);
                                        data += v[i].seriesName + ' : ' + currentDistance + "km(T:" + totalDistance + 'km)<br/>';

                                    } else if (v[i].seriesName == notRunTotalad || v[i].seriesName == totoil || v[i].seriesName == usoil1 || v[i].seriesName == usoil2 || v[i].seriesName == usoil3 || v[i].seriesName == usoil4) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'L<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else {
                                        data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, totoil, notRunTotalad, usoil1, usoil2, usoil3, usoil4],
                        selected: this.selectedLegend,
                        x: 'left',
                    },

                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: speed,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: dis, //
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.veo
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distance
                        }, {
                            smooth: true,
                            name: totoil,
                            type: 'line',
                            symbol: 'none',
                            color: '#C1232B',
                            data: this.totalad,
                            markPoint: {
                                data: this.markPointData,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: notRunTotalad,
                            type: 'line',
                            symbol: 'none',
                            color: '#E2242B',
                            data: this.notRunOil,
                            markPoint: {
                                data: this.markPointDataOil99,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil1,
                            type: 'line',
                            symbol: 'none',
                            color: '#8E388E',
                            data: this.oil1,
                            markPoint: {
                                data: this.markPointDataOil1,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil2,
                            type: 'line',
                            symbol: 'none',
                            color: '#FF4500',
                            data: this.oil2,
                            markPoint: {
                                data: this.markPointDataOil2,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil3,
                            type: 'line',
                            symbol: 'none',
                            color: '#2177C7',
                            data: this.oil3,
                            markPoint: {
                                data: this.markPointDataOil3,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil4,
                            type: 'line',
                            symbol: 'none',
                            color: '#B05432',
                            data: this.oil4,
                            markPoint: {
                                data: this.markPointDataOil4,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates
                        },
                        {
                            smooth: true,
                            name: reissue,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devReissue
                        },
                    ]
                };
            },
            getMarkerSymbol: function(icon, markerRotation) {
                return {
                    'markerFile': './images/carstate/' + icon + '_green_0.png',
                    'markerWidth': 30,
                    'markerHeight': 30,
                    'markerRotation': -markerRotation,
                    // 'markerDy': markerDy,
                    // 'markerDx': 0,
                    "markerHorizontalAlignment": "middle",
                    "markerVerticalAlignment": "middle",
                };
            }
        },

        mounted: function() {
            var me = this;
            this.recvtime = [];
            this.veo = [];
            this.distance = [];
            this.totalad = [];
            this.notRunOil = [];
            this.markPointData = [];
            this.markPointDataOil1 = [];
            this.markPointDataOil2 = [];
            this.markPointDataOil3 = [];
            this.markPointDataOil4 = [];
            this.markPointDataOil99 = [];
            this.oil1 = [];
            this.oil2 = [];
            this.oil3 = [];
            this.oil4 = [];
            this.srcad0 = [];
            this.srcad1 = [];
            this.srcad2 = [];
            this.srcad3 = [];
            this.devStates = [];
            this.devReissue = [];

            var usoil2 = vRoot.$t('reportForm.oil2');
            var usoil3 = vRoot.$t('reportForm.oil3');
            var usoil4 = vRoot.$t('reportForm.oil4');

            if (isZh) {
                this.selectedLegend = {
                    '油液2': false,
                    '油液3': false,
                    '油液4': false,
                }
            } else {
                this.selectedLegend = {
                    'Tank2': false,
                    'Tank3': false,
                    'Tank4': false,
                }
            }

            me.mapIns = utils.initWindowMap('add-leak-map');
            me.chartsIns = echarts.init(document.getElementById('add-leak-charts'));
            me.chartsIns.setOption(me.getChartsOption(), true);
            me.month = new Date();
            me.groupslist = groupslist;
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
                me.chartsIns.resize();
            }
            this.chartsIns.on('legendselectchanged', function(param) {
                me.selectedLegend = param.selected;
            });

            this.chartsIns.getZr().on('click', function(params) {
                var pointInPixel = [params.offsetX, params.offsetY];
                if (me.chartsIns.containPixel('grid', pointInPixel)) {
                    var xIndex = me.chartsIns.convertFromPixel({ seriesIndex: 0 }, [params.offsetX, params.offsetY])[0];
                    var track = me.oilTracks[xIndex];
                    if (track && me.carMarker) {
                        me.carMarker.setCoordinates(track.point);
                        me.carMarker.setSymbol(me.getMarkerSymbol(carIconTypes[me.queryDeviceId], track.course));
                    }

                }
            });
        }
    })
}



function oilMonthDetail(groupslist) {
    vueInstanse = new Vue({
        el: '#oil-month-detail',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            isSpin: false,
            tableHeight: 100,
            groupslist: [],
            month: '',
            columns: [{
                    title: vRoot.$t("reportForm.time"),
                    key: 'statisticsday',
                    width: 105,
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                    width: 125,
                },
                {
                    title: vRoot.$t('reportForm.mileage') + '(km)',
                    key: 'totaldistance',
                    width: 110,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.oilConsumption") + '(L)',
                    key: 'totaloil',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.fuelVolume") + '(L)',
                    key: 'addoil',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.oilLeakage") + '(L)',
                    key: 'leakoil',
                    width: 130,
                    sortable: true,
                },


                { title: vRoot.$t('reportForm.idleoil') + '(L)', key: 'idleoil', width: 120, sortable: true, },

                {
                    title: vRoot.$t("reportForm.workingHours") + '(H)',
                    key: 'totalacc',
                    width: 140,
                    sortable: true,

                },
                { title: vRoot.$t('reportForm.runoilper100km') + '(L)', key: 'runoilper100km', width: 160, sortable: true, },
                {
                    title: vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                    key: 'oilper100km',
                    width: 160,
                    sortable: true,
                },
                {
                    title: vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                    key: 'oilperhour',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                    key: 'averagespeed',
                    width: 140,
                    sortable: true,
                },
                { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalnotrunningad', sortable: true, width: 145, },
                { title: vRoot.$t("reportForm.addnotrunningad") + '(L)', key: 'addnotrunningad', sortable: true, width: 155, },
                { title: vRoot.$t("reportForm.leaknotrunningad") + '(L)', key: 'leaknotrunningad', sortable: true, width: 155, },

            ],
            tableData: [],
            dateOptions: {
                disabledDate: function(date) {
                    return (date && date.valueOf()) > Date.now();
                }
            },
        },
        methods: {
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.time"),
                        vRoot.$t('reportForm.mileage') + '(km)',
                        vRoot.$t("reportForm.oilConsumption") + '(L)',
                        vRoot.$t("reportForm.fuelVolume") + '(L)',
                        vRoot.$t("reportForm.oilLeakage") + '(L)',
                        vRoot.$t('reportForm.idleoil') + '(L)',
                        vRoot.$t("reportForm.workingHours") + '(H)',
                        vRoot.$t('reportForm.runoilper100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                        vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                        vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                        vRoot.$t("reportForm.addnotrunningad") + '(L)',
                        vRoot.$t("reportForm.leaknotrunningad") + '(L)',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.statisticsday);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.totaloil);
                    itemArr.push(item.addoil);
                    itemArr.push(item.leakoil);
                    itemArr.push(item.idleoil);
                    itemArr.push(item.totalacc);
                    itemArr.push(item.runoilper100km);
                    itemArr.push(item.oilper100km);
                    itemArr.push(item.oilperhour);
                    itemArr.push(item.averagespeed);
                    itemArr.push(item.totalnotrunningad);
                    itemArr.push(item.addnotrunningad);
                    itemArr.push(item.leaknotrunningad);

                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.oilMonthDetail') + '-' + this.queryDeviceId,
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 130;
            },
            onClickQuery: function() {
                var me = this;
                if (!this.queryDeviceId) {
                    this.$Message.error(me.$t("reportForm.selectDevTip"));
                    return;
                };

                var url = myUrls.reportOilMonthDetail();
                var yearmonth = DateFormat.format(this.month, 'yyyy-MM');
                var yearmonthArr = yearmonth.split("-");
                var data = {
                    year: Number(yearmonthArr[0]),
                    month: Number(yearmonthArr[1]),
                    offset: timeDifference,
                    deviceids: [this.queryDeviceId]
                }
                utils.sendAjax(url, data, function(resp) {
                    me.queryDateRange = yearmonth;
                    if (resp.devices) {
                        var records = resp.devices[0].records;
                        records.forEach(function(item) {
                            item.devicename = vstore.state.deviceInfos[item.deviceid] ? vstore.state.deviceInfos[item.deviceid].devicename : item.deviceid;
                            var totalacc = (item.totalacc / 1000 / 3600).toFixed(2);
                            item.idleoil = item.idleoil / 100;
                            item.runoilper100km = item.runoilper100km;
                            item.totaldistance = (item.totaldistance / 1000).toFixed(2)
                            item.totalacc = totalacc;
                            item.totaloil = item.totaloil / 100;
                            item.addoil = item.addoil / 100;
                            item.leakoil = item.leakoil / 100;
                            item.totalnotrunningad = item.totalnotrunningad / 100;
                            item.addnotrunningad = item.addnotrunningad / 100;
                            item.leaknotrunningad = item.leaknotrunningad / 100;
                            if (item.totaldistance == 0 || item.totalacc == 0) {
                                item.averagespeed = 0
                            } else {
                                item.averagespeed = (Number(item.totaldistance) / Number(totalacc)).toFixed(2);
                            }
                        })
                        me.tableData = records ? records : [];
                    }
                });
            },
        },

        mounted: function() {
            var me = this;
            me.month = new Date();
            me.groupslist = groupslist;
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}

function oilMonthReport() {
    vueInstanse = new Vue({
        el: '#month-oil',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            month: '',
            columns: [],
            tableData: [],
            currentIndex: 1,
            dateOptions: {
                disabledDate: function(date) {
                    return (date && date.valueOf()) > Date.now();
                }
            },

            columnsDetail: [{
                    title: vRoot.$t("reportForm.time"),
                    key: 'statisticsday',
                    width: 105,
                    fixed: 'left'
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                    width: 125,
                },
                { title: vRoot.$t('reportForm.runoilper100km') + '(L)', key: 'runoilper100km', width: 160, sortable: true, },
                {
                    title: vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                    key: 'oilper100km',
                    width: 160,
                    sortable: true,
                },
                {
                    title: vRoot.$t('reportForm.mileage') + '(km)',
                    key: 'totaldistance',
                    width: 110,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.oilConsumption") + '(L)',
                    key: 'totaloil',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.fuelVolume") + '(L)',
                    key: 'addoil',
                    width: 130,
                    sortable: true,
                },
                {
                    title: vRoot.$t("reportForm.oilLeakage") + '(L)',
                    key: 'leakoil',
                    width: 130,
                    sortable: true,
                },

                { title: vRoot.$t('reportForm.idleoil') + '(L)', key: 'idleoil', width: 120, sortable: true, },
                { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalnotrunningad', sortable: true, width: 145, },
                { title: vRoot.$t("reportForm.addnotrunningad") + '(L)', key: 'addnotrunningad', sortable: true, width: 155, },
                { title: vRoot.$t("reportForm.leaknotrunningad") + '(L)', key: 'leaknotrunningad', sortable: true, width: 155, },

                {
                    title: vRoot.$t("reportForm.workingHours") + '(H)',
                    key: 'totalaccStr',
                    width: 140,
                    sortable: true,

                },

                {
                    title: vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                    key: 'oilperhour',
                    width: 140,
                    sortable: true,
                },
                {
                    title: vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                    key: 'averagespeed',
                    width: 140,
                    sortable: true,
                },

            ],
            tableDataDetail: [],
            model: false
        },
        methods: {
            onDbClickRowTetail: function(row) {
                var deviceid = row.deviceid.replace('\t', '');
                var day = row.statisticsday;
                this.$Modal.confirm({
                    title: vRoot.$t('rule.titleTipi'),
                    content: isZh ? '是否跳转到时间油液报表？' : 'Jump to time fluid report ?',
                    onOk: function() {
                        reportDeviceId = deviceid;
                        reportTimeFrame = [day, day];
                        vRoot.$children[3].activeName = 'timeOilConsumption';
                        vRoot.$children[3].selectditem('timeOilConsumption');
                        // vRoot.$children[3].$refs.navMenu.updateOpened();
                    }
                })
            },
            onDbClickRow: function(row) {
                var tableDataDetail = [];
                row.records.forEach(function(item) {
                    var devicename = vstore.state.deviceInfos[item.deviceid] ? vstore.state.deviceInfos[item.deviceid].devicename : item.deviceid;
                    var totalacc = (item.totalacc / 1000 / 3600).toFixed(2);
                    var idleoil = item.idleoil / 100;
                    var runoilper100km = item.runoilper100km;
                    var totaldistance = (item.totaldistance / 1000).toFixed(2)
                    var totalaccStr = totalacc;
                    var totaloil = item.totaloil / 100;
                    var addoil = item.addoil / 100;
                    var leakoil = item.leakoil / 100;
                    var totalnotrunningad = item.totalnotrunningad / 100;
                    var addnotrunningad = item.addnotrunningad / 100;
                    var leaknotrunningad = item.leaknotrunningad / 100;


                    tableDataDetail.push({
                        deviceid: '\t' + item.deviceid,
                        statisticsday: item.statisticsday,
                        devicename: devicename,
                        averagespeed: item.avgspeed.toFixed(2),
                        idleoil: idleoil,
                        runoilper100km: runoilper100km,
                        totaldistance: totaldistance,
                        totalaccStr: totalaccStr,
                        totaloil: totaloil,
                        addoil: addoil,
                        leakoil: leakoil,
                        oilper100km: item.oilper100km,
                        oilperhour: item.oilperhour,
                        totalnotrunningad: totalnotrunningad,
                        addnotrunningad: addnotrunningad,
                        leaknotrunningad: leaknotrunningad,
                    })
                })
                this.tableDataDetail = tableDataDetail;
                this.model = true;
            },
            exportDataDetail: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.time"),
                        vRoot.$t('reportForm.runoilper100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                        vRoot.$t('reportForm.mileage') + '(km)',
                        vRoot.$t("reportForm.oilConsumption") + '(L)',
                        vRoot.$t("reportForm.fuelVolume") + '(L)',
                        vRoot.$t("reportForm.oilLeakage") + '(L)',
                        vRoot.$t('reportForm.idleoil') + '(L)',
                        vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                        vRoot.$t("reportForm.addnotrunningad") + '(L)',
                        vRoot.$t("reportForm.leaknotrunningad") + '(L)',
                        vRoot.$t("reportForm.workingHours") + '(H)',
                        vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                        vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                    ]
                ];
                this.tableDataDetail.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.statisticsday);
                    itemArr.push(item.runoilper100km);
                    itemArr.push(item.oilper100km);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.totaloil);
                    itemArr.push(item.addoil);
                    itemArr.push(item.leakoil);
                    itemArr.push(item.idleoil);
                    itemArr.push(item.totalnotrunningad);
                    itemArr.push(item.addnotrunningad);
                    itemArr.push(item.leaknotrunningad);
                    itemArr.push(item.totalaccStr);
                    itemArr.push(item.oilperhour);
                    itemArr.push(item.averagespeed);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.oilMonthDetail'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();
            },
            exportData: function() {
                var month = DateFormat.format(this.month, 'yyyy_MM');
                var day = this.getTheMonthDays(this.month);
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.totalMileage"),
                        vRoot.$t("reportForm.totalrunconsumption") + '(L)',
                        vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                        vRoot.$t("reportForm.avgrunoilper100km") + '(L)',
                        vRoot.$t("reportForm.avgoilper100km") + '(L)',
                        vRoot.$t("reportForm.fuelVolume") + '(L)',
                        vRoot.$t("reportForm.oilLeakage") + '(L)',
                        vRoot.$t("reportForm.idleoil") + '(L)',
                        isZh ? '月份' : 'Month',
                    ]
                ];


                for (var i = 0; i < day; i++) {
                    data[0].push(i + 1);
                }

                this.records.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.totaloil);
                    itemArr.push(item.totalnotrunningad);
                    itemArr.push(item.avgrunoilper100km);
                    itemArr.push(item.avgoilper100km);
                    itemArr.push(item.addoil);
                    itemArr.push(item.leakoil);
                    itemArr.push(item.idleoil);
                    itemArr.push(item.month);
                    for (var i = 0; i < day; i++) {
                        var key = 'disAndOil' + (i + 1);
                        itemArr.push(item[key] ? item[key] : '');
                    }
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.oilMonthReport') + '_' + month,
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 175;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportOilMonth();
                    var yearmonth = DateFormat.format(this.month, 'yyyy-MM');
                    var yearmonthArr = yearmonth.split("-");
                    var data = {
                        year: Number(yearmonthArr[0]),
                        month: Number(yearmonthArr[1]),
                        offset: timeDifference,
                        deviceids: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {

                        me.loading = false;
                        var month = DateFormat.format(me.month, 'yyyy_MM');
                        if (resp.status === 0) {
                            var dayLen = me.getTheMonthDays(me.month);
                            if (resp.devices.length) {
                                resp.devices.forEach(function(item, idx) {
                                    item.index = idx + 1;
                                    var deviceid = item.deviceid;
                                    var records = item.records;
                                    var totaldistance = 0;
                                    var totaloil = 0;
                                    var totalnotrunningad = 0;
                                    var addoil = 0;
                                    var leakoil = 0;
                                    var idleoil = 0;
                                    for (var j = 0; j < dayLen; j++) {
                                        var day = records[j];
                                        if (day) {
                                            var key = day.statisticsday.split('-')[2];
                                            var distance = day.totaldistance;
                                            totaldistance += distance;
                                            item['day' + String(parseInt(key))] = utils.getMileage(distance);
                                            item['day' + String(parseInt(key)) + 'oil'] = day.totaloil;
                                            totaloil += day.totaloil;
                                            totalnotrunningad += day.totalnotrunningad;
                                            addoil += day.addoil;
                                            leakoil += day.leakoil;
                                            idleoil += day.idleoil;
                                            item['disAndOil' + Number(key)] = item['day' + String(parseInt(key))] + '/' + (item['day' + String(parseInt(key)) + 'oil'] / 100) + 'L';
                                            day.yearmonth = yearmonthArr[0] + "-" + yearmonthArr[1];

                                        }
                                    }
                                    for (var k = 0; k < dayLen; k++) {
                                        var key = 'day' + (k + 1);
                                        if (!item[key]) {
                                            item[key] = '-';
                                        }
                                    }



                                    item.totaloil = (totaloil / 100);
                                    item.totalnotrunningad = (totalnotrunningad / 100);
                                    item.addoil = (addoil / 100);
                                    item.leakoil = (leakoil / 100);
                                    item.idleoil = (idleoil / 100);
                                    item.month = month;
                                    item.devicename = "\t" + (vstore.state.deviceInfos[deviceid] ? vstore.state.deviceInfos[deviceid].devicename : deviceid);
                                    item.deviceid = "\t" + deviceid;
                                    item.totaldistance = utils.getMileage(totaldistance);
                                });
                                me.records = resp.devices;
                                me.tableData = me.records.slice(0, 20);
                                me.total = me.records.length;

                            } else {
                                me.tableData = [];
                            };
                            me.currentIndex = 1;
                        } else {
                            me.tableData = [];
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            getTheMonthDays: function(date) {
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                year = month == 12 ? year + 1 : year;
                month = month == 12 ? 1 : month;
                return new Date(new Date(year, month, 1) - 1).getDate();
            },
            getInfoContent: function(h, info) {

                var children = [];
                if (info) {
                    var idleoil = info.idleoil / 100;
                    var runoilper100km = info.runoilper100km;
                    // var totaldistance = (info.totaldistance / 1000).toFixed(2)
                    var totalaccStr = (info.totalacc / 1000 / 3600).toFixed(2);;
                    var addoil = info.addoil / 100;
                    var leakoil = info.leakoil / 100;
                    var addnotrunningad = info.addnotrunningad / 100;
                    var leaknotrunningad = info.leaknotrunningad / 100;

                    children.push(h('div', vRoot.$t("reportForm.fuelVolume") + ':' + addoil + 'L'));
                    children.push(h('div', vRoot.$t("reportForm.oilLeakage") + ':' + leakoil + 'L'));
                    children.push(h('div', vRoot.$t("reportForm.idleoil") + ':' + idleoil + 'L'));
                    children.push(h('div', vRoot.$t("reportForm.workingHours") + ':' + totalaccStr + 'h'));
                    children.push(h('div', vRoot.$t("reportForm.runoilper100km") + ':' + runoilper100km + 'L'));
                    children.push(h('div', vRoot.$t("reportForm.fuelConsumption100km") + ':' + info.oilper100km + 'L'));
                    children.push(h('div', vRoot.$t("reportForm.averageSpeed") + ':' + info.avgspeed.toFixed(2) + 'L'));
                    children.push(h('div', vRoot.$t("reportForm.addnotrunningad") + ':' + addnotrunningad + 'L'));
                    children.push(h('div', vRoot.$t("reportForm.leaknotrunningad") + ':' + leaknotrunningad + 'L'));


                } else {
                    children.push(h('div', {}, isZh ? '空' : "Empty"));
                }

                return children;
            },
            getDayColor: function(info) {
                var color = 'grey';
                if (info) {
                    if (info.leakoil > 0) {
                        color = 'red';
                    } else {
                        if (info.addoil > 0) {
                            color = '#2DB7F5';
                        }
                    }
                }
                return color;
            }
        },
        watch: {
            month: function(newMonth) {
                // sortable: true,
                var self = this;
                var columns = [
                    { key: 'index', width: 50, title: vRoot.$t("reportForm.index"), fixed: 'left' },
                    { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 80, fixed: 'left' },
                    { title: vRoot.$t("reportForm.totalMileage"), key: 'totaldistance', sortable: true, width: 80, fixed: 'left' },
                    { title: vRoot.$t("reportForm.totalrunconsumption") + '(L)', key: 'totaloil', sortable: true, width: 120, fixed: 'left' },
                    { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalnotrunningad', sortable: true, width: 130, fixed: 'left' },
                    { title: vRoot.$t("reportForm.avgrunoilper100km"), key: 'avgrunoilper100km', width: 110, fixed: 'left' },
                    { title: vRoot.$t("reportForm.avgoilper100km"), key: 'avgoilper100km', width: 80, fixed: 'left' },
                    { title: vRoot.$t("reportForm.fuelVolume"), key: 'addoil', width: 70, fixed: 'left' },
                    { title: vRoot.$t("reportForm.oilLeakage"), key: 'leakoil', width: 70, fixed: 'left' },
                    { title: vRoot.$t("reportForm.idleoil"), key: 'idleoil', width: 70, fixed: 'left' },
                ];

                var day = this.getTheMonthDays(newMonth);

                for (var i = 1; i <= day; i++) {
                    var key = 'day' + i;
                    (function(key, i) {
                        columns.push({
                            key: key,
                            title: i,
                            width: 88,
                            align: 'center',
                            sortable: true,
                            render: function(h, params) {
                                var row = params.row;
                                var oil = row[key + 'oil'];
                                var dayRecord = null;
                                row.records.forEach(function(item) {
                                    var yearmonth = item.yearmonth + (i > 9 ? '-' + i : '-0' + i);
                                    if (item.statisticsday == yearmonth) {
                                        dayRecord = item
                                    }
                                })

                                var contentChildren = self.getInfoContent(h, dayRecord);
                                var color = self.getDayColor(dayRecord);
                                return h('Poptip', {
                                    props: {
                                        // width: 240,
                                        // height: 60,
                                        // content: content
                                        // popperClass: 'poptip-popper-class',
                                        placement: "bottom"
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            // type: 'info',
                                            size: 'small'
                                        },
                                        style: {
                                            width: '70px',
                                            backgroundColor: color,
                                            color: '#ffffff'
                                        }
                                    }, [
                                        h('p', {}, row[key]),
                                        h('p', {}, oil ? (row[key + 'oil'] / 100) + 'L' : '-'),
                                    ]),
                                    h(
                                        'div', {
                                            slot: 'content',
                                            attrs: {
                                                slot: "content"
                                            }
                                        }, contentChildren
                                    )
                                ]);
                            }
                        })
                    })(key, i)
                }

                this.columns = columns;
            },
        },
        mounted: function() {
            var me = this;
            me.month = new Date();
            me.records = [];
            reportTimeFrame = null;
            me.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


function groupMileage(groupslist) {
    vueInstanse = new Vue({
        el: '#group-mileage',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            columns: [
                { key: 'index', width: 70, title: vRoot.$t("reportForm.index") },
                { title: vRoot.$t("alarm.devName"), key: 'devicename' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid' },
                { title: vRoot.$t("monitor.groupName"), key: 'groupName', },
                { title: vRoot.$t("reportForm.totalMileage") + '(km)', key: 'totaldistance', sortable: true },
                { title: vRoot.$t("reportForm.startDate"), key: 'starttimeStr' },
                { title: vRoot.$t("reportForm.endDate"), key: 'endtimeStr' },
                { title: vRoot.$t("reportForm.minMileage") + '(km)', key: 'startdistance' },
                { title: vRoot.$t("reportForm.maxMileage") + '(km)', key: 'enddistance' },

            ],
            tableData: [],
            currentIndex: 1,
        },
        methods: {
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("monitor.groupName"),
                        vRoot.$t("reportForm.totalMileage") + '(km)',
                        vRoot.$t("reportForm.startDate"),
                        vRoot.$t("reportForm.endDate"),
                        vRoot.$t("reportForm.minMileage") + '(km)',
                        vRoot.$t("reportForm.maxMileage") + '(km)',
                    ]
                ];
                this.records.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.groupName);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.starttimeStr);
                    itemArr.push(item.endtimeStr);
                    itemArr.push(item.startdistance);
                    itemArr.push(item.enddistance);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.reportmileagesummary'),
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();

            },
            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 170;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportMileageSummary();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                        if (resp.status === 0) {
                            if (resp.records.length) {
                                resp.records.forEach(function(item, index) {
                                    item.index = index + 1;
                                    if (item.starttime == 0) {
                                        item.starttimeStr = me.$t("reportForm.empty");
                                    } else {
                                        item.starttimeStr = DateFormat.longToLocalDateTimeStr(item.starttime);
                                    }
                                    if (item.endtime == 0) {
                                        item.endtimeStr = me.$t("reportForm.empty");;
                                    } else {
                                        item.endtimeStr = DateFormat.longToLocalDateTimeStr(item.endtime);
                                    }
                                    item.devicename = vstore.state.deviceInfos[item.deviceid] ? vstore.state.deviceInfos[item.deviceid].devicename : item.deviceid;
                                    item.enddistance != 0 ? item.enddistance = (item.enddistance / 1000).toFixed(2) : null;
                                    item.startdistance != 0 ? item.startdistance = (item.startdistance / 1000).toFixed(2) : null;
                                    item.totaldistance != 0 ? item.totaldistance = (item.totaldistance / 1000).toFixed(2) : null;
                                    item.groupName = utils.getGroupName(groupslist, item.deviceid);
                                });
                                me.records = resp.records;
                                me.tableData = me.records.slice(0, 20);
                                me.total = me.records.length;

                            } else {
                                me.tableData = [];
                            };
                            me.currentIndex = 1;
                        } else {
                            me.tableData = [];
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            me.records = [];
            me.handleSelectdDate(1);
            me.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


// 停车表报
function parkDetails(groupslist) {
    vueInstanse = new Vue({
        el: '#park-details',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            mapModal: false,
            mapType: utils.getMapType(),
            mapInstance: null,
            markerIns: null,
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            columns: [
                { title: vRoot.$t("reportForm.index"), key: 'index', width: 60, align: 'center' },
                { title: vRoot.$t("alarm.devName"), key: 'deviceName', width: 160 },
                { title: vRoot.$t("reportForm.startDate"), key: 'startDate', width: 180 },
                { title: vRoot.$t("reportForm.endDate"), key: 'endDate', width: 180 },
                { title: vRoot.$t("reportForm.parkDate"), key: 'parkTimeStr', width: 160 },
                {
                    title: vRoot.$t("reportForm.lon") + "," + vRoot.$t("reportForm.lat"),
                    width: 160,
                    key: 'callon_callat',
                    render: function(h, params) {
                        return h('div', [
                            h('a', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        utils.showWindowMap(vueInstanse, params);
                                    }
                                }
                            }, params.row.callon_callat)
                        ]);
                    }
                },
                {
                    title: vRoot.$t("reportForm.address"),
                    key: 'address',
                    render: function(h, params) {
                        var disabled = params.row.disabled;
                        var node = null;
                        if (disabled) {
                            node = h('div', {
                                props: {},
                                style: {},
                                on: {}
                            }, params.row.address);
                        } else {
                            node = h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                    disabled: params.row.disabled,
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.getAddress(params);
                                    }
                                }
                            }, vRoot.$t("reportForm.getAddress"));
                        }
                        return node;
                    }
                },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 100,
                    render: function(h, params) {
                        var row = params.row;
                        return h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small',
                            },
                            on: {
                                click: function() {
                                    var twoMinutes = 60 * 1000 * 2;
                                    var deviceid = row.deviceid;
                                    var devicename = row.deviceName;
                                    var starttime = row.starttime - twoMinutes;
                                    var endtime = row.endtime + twoMinutes;

                                    var toDay = DateFormat.longToDateStr(starttime, timeDifference);
                                    if (toDay != DateFormat.longToDateStr(endtime, timeDifference)) {
                                        endtime = DateFormat.formatToDateTime(toDay + " 23:59:59");
                                    };

                                    window.open('videoback.html?deviceid=' + deviceid + '&token=' + token + '&devicename=' + devicename + '&starttime=' + starttime + '&endtime=' + endtime);
                                }
                            }
                        }, vRoot.$t("monitor.videoPlayback"));

                    }
                }
            ],
            tableData: [],
            interval: '3',
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("reportForm.startDate"),
                        vRoot.$t("reportForm.endDate"),
                        vRoot.$t("reportForm.parkDate"),
                        vRoot.$t("reportForm.parkDate") + '(H)',
                        vRoot.$t("reportForm.lon") + "," + vRoot.$t("reportForm.lat"),
                        vRoot.$t("reportForm.address")
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.deviceName);
                    itemArr.push(item.startDate);
                    itemArr.push(item.endDate);
                    itemArr.push(item.parkTimeStr);
                    itemArr.push(item.parkTime);
                    itemArr.push(item.callon_callat);
                    itemArr.push(item.address);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.parkDetails') + '-' + this.queryDeviceId,
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();

            },
            onChange: function(value) {
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 130;
                this.posiDetailHeight = wHeight - 104;
            },
            onClickQuery: function() {
                if (this.queryDeviceId) {
                    var me = this;
                    var url = myUrls.reportParkDetail();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceid: this.queryDeviceId,
                        interval: Number(this.interval)
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                        if (resp.status == 0) {
                            if (resp.records && resp.records.length) {
                                var newRecords = [];
                                var deviceName = vstore.state.deviceInfos[me.queryDeviceId].devicename;
                                resp.records.forEach(function(item, index) {
                                    var callon = item.callon.toFixed(5);
                                    var callat = item.callat.toFixed(5);
                                    var parkTime = ((item.endtime - item.starttime) / 1000 / 3600).toFixed(2);
                                    var parkTimeStr = utils.timeStamp(item.endtime - item.starttime, isZh);
                                    var address = null;
                                    if (item.address) {
                                        address = item.address;
                                    } else {
                                        address = LocalCacheMgr.getAddress(callon, callat);
                                    }
                                    newRecords.push({
                                        index: index + 1,
                                        deviceName: deviceName,
                                        startDate: DateFormat.longToLocalDateTimeStr(item.starttime),
                                        endDate: DateFormat.longToLocalDateTimeStr(item.endtime),
                                        starttime: item.starttime,
                                        endtime: item.endtime,
                                        parkTime: parkTime,
                                        parkTimeStr: parkTimeStr,
                                        deviceid: data.deviceid,
                                        callon_callat: callon + ',' + callat,
                                        callon: callon,
                                        callat: callat,
                                        address: address,
                                        disabled: address ? true : false
                                    });
                                });
                                me.tableData = newRecords;
                            } else {
                                me.tableData = [];
                            }
                        } else {
                            me.tableData = [];
                        }
                    });
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            getAddress: function(params) {
                var me = this;
                var row = params.row;
                var index = params.index;
                utils.queryAddress(row, function(address) {
                    me.tableData[index].address = address;
                    me.tableData[index].disabled = true;
                    LocalCacheMgr.setAddress(row.callon, row.callat, address);
                });
            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('posi-map');
            },
        },
        mounted: function() {
            var me = this;
            this.initMap();
            this.groupslist = groupslist;
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


function checkReport(groupslist) {
    vueInstanse = new Vue({
        el: '#check-report',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            checktype: '0', //0 全部 All 1 上报签到 CheckIn 2 下班签退 
            activeTab: 'tabTotal',
            mapModal: false,
            mapType: utils.getMapType(),
            mapInstance: null,
            markerIns: null,
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            detailTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            allAccColumns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 160,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getCheckDetailTableData(params.row.records);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.checkDetails") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                },
                {
                    title: isZh ? '次数' : 'Count',
                    key: 'opennumber',
                },
            ],
            allAccTableData: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 160 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 160 },
                { title: vRoot.$t("reportForm.status"), key: isZh ? 'stralarm' : 'stralarmen' },
                { title: vRoot.$t("reportForm.date"), key: 'lasttimeStr' },
                { title: vRoot.$t("reportForm.address"), key: 'address' },
            ],
            tableData: [],
        },
        methods: {
            onRowClick: function(row) {
                this.queryTracks(row);
            },
            getMarkerSymbol: function(icon, markerRotation) {
                return {
                    'markerFile': './images/carstate/' + icon + '_green_0.png',
                    'markerWidth': 30,
                    'markerHeight': 30,
                    'markerRotation': -markerRotation,
                    // 'markerDy': markerDy,
                    // 'markerDx': 0,
                    "markerHorizontalAlignment": "middle",
                    "markerVerticalAlignment": "middle",
                };
            },
            queryTracks: function(row) {

                if (!row.deviceid) {
                    return;
                };
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: DateFormat.longToLocalDateTimeStr(row.lastalarmtime - 60 * 10 * 1000),
                        endtime: DateFormat.longToLocalDateTimeStr(row.lastalarmtime + 60 * 10 * 1000),
                        timezone: timeDifference
                    };

                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.markersAndLineLayerToMap(records, row);
                        } else {

                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            markersAndLineLayerToMap: function(tracks, row) {
                var begintime = row.lastalarmtime;
                var endtime = row.lastalarmtime;

                var vueInstanse = this;
                if (vueInstanse.markerLayer != null) {
                    vueInstanse.mapIns.removeLayer(vueInstanse.markerLayer);
                }
                var isBMap = utils.getMapType();
                var points = [];
                var firstPoints = [];
                var addLeakPoints = [];
                var lastPoints = [];
                tracks.forEach(function(track, index) {
                    track.idx = index;
                    track.totaldistance = track.totaldistance / 1000;
                    track.totalad = track.totalad / 100;
                    track.ad0 = track.ad0 / 100;
                    track.ad1 = track.ad1 / 100;
                    track.ad2 = track.ad2 / 100;
                    track.ad3 = track.ad3 / 100;
                    track.totalnotrunningad = track.totalnotrunningad / 100;
                    if (isBMap) {
                        var g_lon_lat = wgs84tobd09(track.callon, track.callat);
                        track.point = {
                            y: g_lon_lat[1],
                            x: g_lon_lat[0]
                        };
                    } else {
                        var lng_lat = wgs84togcj02(track.callon, track.callat);
                        track.point = {
                            y: lng_lat[1],
                            x: lng_lat[0]
                        };
                    }
                    if (track.updatetime < begintime) {
                        firstPoints.push(track.point);
                    } else if (begintime <= track.updatetime && track.updatetime <= endtime) {
                        addLeakPoints.push(track.point);
                    } else if (track.updatetime > endtime) {
                        lastPoints.push(track.point);
                    }
                    points.push(track.point);
                })
                if (firstPoints.length) {
                    addLeakPoints.unshift(firstPoints[firstPoints.length - 1])
                }
                if (lastPoints.length) {
                    addLeakPoints.push(lastPoints[0]);
                }
                var sTrack = tracks[0];

                var smarker = new maptalks.Marker(
                    [sTrack.point.x, sTrack.point.y], {
                        symbol: {
                            'markerFile': './images/icon_st.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': 0,
                            'markerDy': 0,
                            'markerDx': 0,
                        },
                        zIndex: 999
                    }
                );

                var eTrack = tracks[tracks.length - 1];
                var emarker = new maptalks.Marker(
                    [eTrack.point.x, eTrack.point.y], {
                        symbol: {
                            'markerFile': './images/icon_en.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': 0,
                            'markerDy': 0,
                            'markerDx': 0,
                        },
                        zIndex: 999
                    }
                );

                var firstLineString = new maptalks.LineString(
                    firstPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'red'],
                                    [1.00, 'red']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })
                var centerLineString = new maptalks.LineString(
                    addLeakPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'green'],
                                    [1.00, 'green']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })

                var carTrackIndex = utils.getCalMarkPointIndex(tracks, row);
                var carTrack = tracks[carTrackIndex];
                this.carMarker = new maptalks.Marker(
                    [carTrack.point.x, carTrack.point.y], {
                        symbol: this.getMarkerSymbol(carIconTypes[row.deviceid], carTrack.course)
                    }
                );

                var lastLineString = new maptalks.LineString(
                    lastPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'red'],
                                    [1.00, 'red']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })


                vueInstanse.markerLayer = new maptalks.VectorLayer('marker', [smarker, emarker, firstLineString, lastLineString, centerLineString, this.carMarker]);
                vueInstanse.markerLayer.addTo(vueInstanse.mapIns);



                var polygon = new maptalks.Polygon(points);
                this.mapIns.fitExtent(polygon.getExtent(), 0);


            },
            exportData: function() {

                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            isZh ? '次数' : 'Count',
                        ]
                    ];
                    this.allAccTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.opennumber);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.checkStatistics"),
                        data: data,
                        dateRange: this.queryDateRange,
                    }

                } else {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.status"),
                            vRoot.$t("reportForm.date"),
                            vRoot.$t("reportForm.address"),
                        ]
                    ];


                    var deviceid = '';
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];

                        deviceid = item.deviceid;
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(isZh ? item.stralarm : item.stralarmen);
                        itemArr.push(item.lasttimeStr);
                        itemArr.push(item.address);


                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.checkDetails") + ' - ' + deviceid,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                }
                new XlsxCls(options).exportExcel();
            },

            onClickTab: function(name) {
                this.activeTab = name;
            },
            onChange: function(value) {
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 175;
                this.detailTableHeight = wHeight - 585;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length) {
                    var me = this;
                    var url = myUrls.reportCheck();
                    // var url = myUrls.reportAccs();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        devices: deviceids,
                        checktype: Number(this.checktype)
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        me.queryDateRange = data.startday + ' - ' + data.endday;
                        if (resp.status == 0) {
                            me.addressmap = resp.addressmap;
                            if (resp.records && resp.records.length) {
                                me.tableData = [];
                                me.allAccTableData = me.getAllTableData(resp.records);
                            } else {
                                me.tableData = [];
                                me.allAccTableData = [];
                                me.$Message.error(me.$t("reportForm.noRecord"));
                            }
                        } else {
                            me.tableData = [];
                            me.allAccTableData = [];
                        }
                        if (me.activeTab != "tabTotal") {
                            me.onClickTab("tabTotal");
                        }
                    });
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            getAllTableData: function(records) {
                var allAccTableData = [];
                var me = this;
                records.forEach(function(item, index) {
                    var deviceid = item.deviceid;
                    var devicename = vstore.state.deviceInfos[deviceid].devicename;
                    var accObj = {
                        index: index + 1,
                        deviceid: deviceid,
                        opennumber: item.records.length,
                        devicename: devicename,
                        records: item.records
                    };


                    item.records.forEach(function(record, index) {
                        record.index = index + 1;
                        record.deviceid = deviceid;
                        record.devicename = devicename;
                        record.lasttimeStr = DateFormat.longToLocalDateTimeStr(record.lastalarmtime, DateFormat.getOffset());
                        record.address = utils.getMapLatLonAddress(me.addressmap, record.lat, record.lon);
                    });

                    allAccTableData.push(accObj);
                });
                return allAccTableData;
            },
            getCheckDetailTableData: function(records) {
                var me = this;
                records.forEach(function(record, index) {
                    if (index == 0) {
                        record._highlight = true;
                        me.onRowClick(record);
                    } else {
                        record._highlight = false;
                    };
                })
                me.tableData = deepClone(records);
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },

            showWindowMap: function(row) {
                var isBMap = utils.getMapType() == 'bMap';
                var pointArr = [];
                if (isBMap) {
                    pointArr = wgs84tobd09(Number(row.lon), Number(row.lat));
                } else {
                    pointArr = wgs84togcj02(Number(row.lon), Number(row.lat));
                }

                if (this.markerLayer != null) {
                    this.mapIns.removeLayer(this.markerLayer);
                }

                var marker = new maptalks.Marker(
                    pointArr, {
                        symbol: {
                            'markerFile': './images/carstate/0_green_0.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': -row.course,
                            'markerDy': 15,
                            'markerDx': 0,
                        },
                    }
                );

                this.markerLayer = new maptalks.VectorLayer('marker', [marker]);
                this.markerLayer.addTo(this.mapIns);

                this.mapIns.setZoom(18)
                this.mapIns.setCenter({
                    x: pointArr[0],
                    y: pointArr[1],
                })
            },
        },
        mounted: function() {
            var me = this;
            me.addressmap = null;
            me.queryDevicesTree();
            me.mapIns = utils.initWindowMap('check-report-map');
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


function fenceReport(groupslist) {
    vueInstanse = new Vue({
        el: '#fence-report',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            geofencetype: '0', //0 全部 All 1 上报签到 CheckIn 2 下班签退 
            activeTab: 'tabTotal',
            mapModal: false,
            mapType: utils.getMapType(),
            mapInstance: null,
            markerIns: null,
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            detailTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            allAccColumns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 160,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getCheckDetailTableData(params.row.records);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.fenceDetails") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                },
                {
                    title: isZh ? '次数' : 'Count',
                    key: 'opennumber',
                },
            ],
            allAccTableData: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 160 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 160 },
                { title: vRoot.$t("reportForm.status"), key: isZh ? 'stralarm' : 'stralarmen' },
                { title: vRoot.$t("reportForm.selectTime"), key: 'lastalarmtimeStr' },
                { title: vRoot.$t("reportForm.address"), key: 'address' },
            ],
            tableData: [],
        },
        methods: {
            onRowClick: function(row) {
                this.queryTracks(row);
            },
            getMarkerSymbol: function(icon, markerRotation) {
                return {
                    'markerFile': './images/carstate/' + icon + '_green_0.png',
                    'markerWidth': 30,
                    'markerHeight': 30,
                    'markerRotation': -markerRotation,
                    // 'markerDy': markerDy,
                    // 'markerDx': 0,
                    "markerHorizontalAlignment": "middle",
                    "markerVerticalAlignment": "middle",
                };
            },
            queryTracks: function(row) {

                if (!row.deviceid) {
                    return;
                };
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: DateFormat.longToLocalDateTimeStr(row.lastalarmtime - 60 * 10 * 1000),
                        endtime: DateFormat.longToLocalDateTimeStr(row.lastalarmtime + 60 * 10 * 1000),
                        timezone: timeDifference
                    };

                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.markersAndLineLayerToMap(records, row);
                        } else {

                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            markersAndLineLayerToMap: function(tracks, row) {
                var begintime = row.lastalarmtime;
                var endtime = row.lastalarmtime;

                var vueInstanse = this;
                if (vueInstanse.markerLayer != null) {
                    vueInstanse.mapIns.removeLayer(vueInstanse.markerLayer);
                }
                var isBMap = utils.getMapType();
                var points = [];
                var firstPoints = [];
                var addLeakPoints = [];
                var lastPoints = [];
                tracks.forEach(function(track, index) {
                    track.idx = index;
                    track.totaldistance = track.totaldistance / 1000;
                    track.totalad = track.totalad / 100;
                    track.ad0 = track.ad0 / 100;
                    track.ad1 = track.ad1 / 100;
                    track.ad2 = track.ad2 / 100;
                    track.ad3 = track.ad3 / 100;
                    track.totalnotrunningad = track.totalnotrunningad / 100;
                    if (isBMap) {
                        var g_lon_lat = wgs84tobd09(track.callon, track.callat);
                        track.point = {
                            y: g_lon_lat[1],
                            x: g_lon_lat[0]
                        };
                    } else {
                        var lng_lat = wgs84togcj02(track.callon, track.callat);
                        track.point = {
                            y: lng_lat[1],
                            x: lng_lat[0]
                        };
                    }
                    if (track.updatetime < begintime) {
                        firstPoints.push(track.point);
                    } else if (begintime <= track.updatetime && track.updatetime <= endtime) {
                        addLeakPoints.push(track.point);
                    } else if (track.updatetime > endtime) {
                        lastPoints.push(track.point);
                    }
                    points.push(track.point);
                })
                if (firstPoints.length) {
                    addLeakPoints.unshift(firstPoints[firstPoints.length - 1])
                }
                if (lastPoints.length) {
                    addLeakPoints.push(lastPoints[0]);
                }
                var sTrack = tracks[0];

                var smarker = new maptalks.Marker(
                    [sTrack.point.x, sTrack.point.y], {
                        symbol: {
                            'markerFile': './images/icon_st.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': 0,
                            'markerDy': 0,
                            'markerDx': 0,
                        },
                        zIndex: 999
                    }
                );

                var eTrack = tracks[tracks.length - 1];
                var emarker = new maptalks.Marker(
                    [eTrack.point.x, eTrack.point.y], {
                        symbol: {
                            'markerFile': './images/icon_en.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': 0,
                            'markerDy': 0,
                            'markerDx': 0,
                        },
                        zIndex: 999
                    }
                );

                var firstLineString = new maptalks.LineString(
                    firstPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'red'],
                                    [1.00, 'red']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })
                var centerLineString = new maptalks.LineString(
                    addLeakPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'green'],
                                    [1.00, 'green']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })

                var carTrackIndex = utils.getCalMarkPointIndex(tracks, row);
                var carTrack = tracks[carTrackIndex];
                this.carMarker = new maptalks.Marker(
                    [carTrack.point.x, carTrack.point.y], {
                        symbol: this.getMarkerSymbol(carIconTypes[row.deviceid], carTrack.course)
                    }
                );

                var lastLineString = new maptalks.LineString(
                    lastPoints, {
                        symbol: {
                            'lineColor': {
                                'type': 'linear',
                                'colorStops': [
                                    [0.00, 'red'],
                                    [1.00, 'red']
                                ]
                            },
                            'lineWidth': 4
                        }
                    })


                vueInstanse.markerLayer = new maptalks.VectorLayer('marker', [smarker, emarker, firstLineString, lastLineString, centerLineString, this.carMarker]);
                vueInstanse.markerLayer.addTo(vueInstanse.mapIns);



                var polygon = new maptalks.Polygon(points);
                this.mapIns.fitExtent(polygon.getExtent(), 0);


            },
            exportData: function() {

                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            isZh ? '次数' : 'Count',
                        ]
                    ];
                    this.allAccTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.opennumber);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.fenceStatistics"),
                        data: data,
                        dateRange: this.queryDateRange,
                    }

                } else {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.status"),
                            vRoot.$t("reportForm.date"),
                            vRoot.$t("reportForm.address"),
                        ]
                    ];


                    var deviceid = '';
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];

                        deviceid = item.deviceid;
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(isZh ? item.stralarm : item.stralarmen);
                        itemArr.push(item.lastalarmtimeStr);
                        itemArr.push(item.address);


                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.fenceDetails") + ' - ' + deviceid,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                }
                new XlsxCls(options).exportExcel();
            },

            onClickTab: function(name) {
                this.activeTab = name;
            },
            onChange: function(value) {
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 175;
                this.detailTableHeight = wHeight - 585;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length) {
                    var me = this;
                    var url = myUrls.reportGeoFence();
                    // var url = myUrls.reportAccs();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        devices: deviceids,
                        geofencetype: Number(this.checktype)
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        me.queryDateRange = data.startday + ' - ' + data.endday;
                        if (resp.status == 0) {
                            me.addressmap = resp.addressmap;
                            if (resp.records && resp.records.length) {
                                me.tableData = [];
                                me.allAccTableData = me.getAllTableData(resp.records);
                            } else {
                                me.tableData = [];
                                me.allAccTableData = [];
                                me.$Message.error(me.$t("reportForm.noRecord"));
                            }
                        } else {
                            me.tableData = [];
                            me.allAccTableData = [];
                        }
                        if (me.activeTab != "tabTotal") {
                            me.onClickTab("tabTotal");
                        }
                    });
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            getAllTableData: function(records) {
                var allAccTableData = [];
                var me = this;
                records.forEach(function(item, index) {
                    var deviceid = item.deviceid;
                    var devicename = vstore.state.deviceInfos[deviceid].devicename;
                    var accObj = {
                        index: index + 1,
                        deviceid: deviceid,
                        opennumber: item.records.length,
                        devicename: devicename,
                        records: item.records
                    };


                    item.records.forEach(function(record, index) {
                        record.index = index + 1;
                        record.deviceid = deviceid;
                        record.devicename = devicename;
                        record.lastalarmtimeStr = DateFormat.longToLocalDateTimeStr(record.lastalarmtime);
                        record.address = utils.getMapLatLonAddress(me.addressmap, record.lat, record.lon);
                    });

                    allAccTableData.push(accObj);
                });
                return allAccTableData;
            },
            getCheckDetailTableData: function(records) {
                var me = this;
                records.forEach(function(record, index) {
                    if (index == 0) {
                        record._highlight = true;
                        me.onRowClick(record);
                    } else {
                        record._highlight = false;
                    };
                })
                me.tableData = deepClone(records);
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },

            showWindowMap: function(row) {
                var isBMap = utils.getMapType() == 'bMap';
                var pointArr = [];
                if (isBMap) {
                    pointArr = wgs84tobd09(Number(row.lon), Number(row.lat));
                } else {
                    pointArr = wgs84togcj02(Number(row.lon), Number(row.lat));
                }

                if (this.markerLayer != null) {
                    this.mapIns.removeLayer(this.markerLayer);
                }

                var marker = new maptalks.Marker(
                    pointArr, {
                        symbol: {
                            'markerFile': './images/carstate/0_green_0.png',
                            'markerWidth': 30,
                            'markerHeight': 30,
                            'markerRotation': -row.course,
                            'markerDy': 15,
                            'markerDx': 0,
                        },
                    }
                );

                this.markerLayer = new maptalks.VectorLayer('marker', [marker]);
                this.markerLayer.addTo(this.mapIns);

                this.mapIns.setZoom(18)
                this.mapIns.setCenter({
                    x: pointArr[0],
                    y: pointArr[1],
                })
            },
        },
        mounted: function() {
            var me = this;
            me.addressmap = null;
            me.queryDevicesTree();
            me.mapIns = utils.initWindowMap('check-report-map');
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


//acc报表
function accDetails(groupslist) {
    vueInstanse = new Vue({
        el: '#acc-details',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            activeTab: 'tabTotal',
            mapModal: false,
            mapType: utils.getMapType(),
            mapInstance: null,
            markerIns: null,
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference) + ' 00:00:00', DateFormat.longToDateStr(Date.now(), timeDifference) + ' 23:59:59'],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            allAccColumns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 160,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getAccDetailTableData(params.row.records);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.accDetailed") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                },
                {
                    title: vRoot.$t("reportForm.accCount"),
                    key: 'opennumber',
                },
                {
                    title: vRoot.$t("reportForm.accDuration"),
                    key: 'durationStr'
                }
            ],
            allAccTableData: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                { title: vRoot.$t("alarm.devName"), key: 'deviceName', width: 160 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 160 },
                { title: vRoot.$t("reportForm.accstatus"), key: 'accStatus', width: 100 },
                { title: vRoot.$t("reportForm.startDate"), key: 'startDate', width: 180 },
                { title: vRoot.$t("reportForm.endDate"), key: 'endDate', width: 180 },
                { title: vRoot.$t("reportForm.duration"), key: 'durationStr' },
            ],
            tableData: [],
        },
        methods: {
            exportData: function() {

                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.accCount"),
                            vRoot.$t("reportForm.accDuration"),
                            vRoot.$t("reportForm.accDuration"),
                        ]
                    ];
                    this.allAccTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.opennumber);
                        itemArr.push(item.duration);
                        itemArr.push(item.durationStr);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.ignitionStatistics"),
                        data: data,
                        dateRange: this.queryDateRange,
                    }

                } else {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.accstatus"),
                            vRoot.$t("reportForm.startDate"),
                            vRoot.$t("reportForm.endDate"),
                            vRoot.$t("reportForm.duration"),
                            vRoot.$t("reportForm.duration") + '(H)',
                        ]
                    ];

                    var len = this.tableData.length - 1;
                    var deviceid = '';
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];
                        if (len == index) {
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push(item.duration);
                        } else {
                            deviceid = item.deviceid;
                            itemArr.push(index + 1);
                            itemArr.push(item.deviceName);
                            itemArr.push(item.deviceid);
                            itemArr.push(item.accStatus);
                            itemArr.push(item.startDate);
                            itemArr.push(item.endDate);
                            itemArr.push(item.durationStr);
                            itemArr.push(item.duration);
                        }
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.ignitionStatistics") + ' - ' + deviceid,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                }
                new XlsxCls(options).exportExcel();
            },

            onClickTab: function(name) {
                this.activeTab = name;
            },
            onChange: function(value) {

                var lastTimeStr = value[1];
                if (lastTimeStr.indexOf('00:00:00') != -1) {
                    lastTimeStr = lastTimeStr.replace('00:00:00', '23:59:59')
                    value.pop();
                    value.push(lastTimeStr);
                }
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 175;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length) {
                    var me = this;
                    var url = myUrls.reportAccSbyTime();
                    // var url = myUrls.reportAccs();
                    var data = {

                        starttime: this.dateVal[0],
                        endtime: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        me.queryDateRange = data.starttime + ' - ' + data.endtime;
                        if (resp.status == 0) {
                            if (resp.records && resp.records.length) {
                                me.tableData = [];
                                me.allAccTableData = me.getAllaccTableData(resp.records);
                            } else {
                                me.tableData = [];
                                me.allAccTableData = [];
                                me.$Message.error(me.$t("reportForm.noRecord"));
                            }
                        } else {
                            me.tableData = [];
                            me.allAccTableData = [];
                        }
                        if (me.activeTab != "tabTotal") {
                            me.onClickTab("tabTotal");
                        }
                    });
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            getAllaccTableData: function(records) {
                var allAccTableData = [],
                    me = this;
                records.forEach(function(item, index) {
                    var accObj = {
                            index: index + 1,
                            deviceid: "\t" + item.deviceid,
                            opennumber: 0,
                            duration: "",
                            devicename: vstore.state.deviceInfos[item.deviceid].devicename,
                            records: item.records
                        },
                        duration = 0;
                    item.records.forEach(function(deviceAcc) {
                        if (deviceAcc.accstate == 3) {
                            duration += deviceAcc.endtime - deviceAcc.begintime;
                            accObj.opennumber++;
                        }
                    });
                    accObj.duration = (duration / 1000 / 3600).toFixed(2);;
                    accObj.durationStr = utils.timeStamp(duration, isZh);
                    allAccTableData.push(accObj);
                });
                return allAccTableData;
            },
            getAccDetailTableData: function(records) {
                var newRecords = [],
                    me = this;
                var accOnTime = 0;
                var accOffTime = 0;
                records.sort(function(a, b) {
                    return a.begintime - b.begintime;
                });
                records.forEach(function(item, index) {
                    var deviceName = vstore.state.deviceInfos[item.deviceid].devicename;
                    var duration = ((item.endtime - item.begintime) / 1000 / 3600).toFixed(2);
                    var durationStr = utils.timeStamp(item.endtime - item.begintime, isZh);
                    var accStatus = "";
                    if (item.accstate == 0) {
                        accStatus = me.$t("reportForm.notEnabled");
                    } else if (item.accstate == 3) {
                        accStatus = me.$t("reportForm.open");
                        accOnTime += (item.endtime - item.begintime);
                    } else if (item.accstate == 2) {
                        accOffTime += (item.endtime - item.begintime);
                        accStatus = me.$t("reportForm.stalling");
                    }
                    newRecords.push({
                        index: index + 1,
                        deviceid: item.deviceid,
                        deviceName: deviceName,
                        startDate: DateFormat.longToLocalDateTimeStr(item.begintime),
                        endDate: DateFormat.longToLocalDateTimeStr(item.endtime),
                        accStatus: accStatus,
                        duration: duration,
                        durationStr: durationStr
                    });
                });
                newRecords.push({
                    durationStr: this.$t("reportForm.accOnTime") + ':' + utils.timeStamp(accOnTime, isZh) + ',' + this.$t("reportForm.accOffTime") + ':' + utils.timeStamp(accOffTime, isZh)
                })
                me.tableData = newRecords;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            me.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })

}

function rotateReport(groupslist) {
    vueInstanse = new Vue({
        el: '#rotate-report',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            activeTab: 'tabTotal',
            mapModal: false,
            mapType: utils.getMapType(),
            mapInstance: null,
            markerIns: null,
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            allAccColumns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                {
                    title: vRoot.$t("alarm.action"),
                    render: function(h, params) {

                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    editObject = params.row;
                                    vueInstanse.getRotateDetailTableData(params.row.records);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.rotationDetails") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                    width: 160,
                },
                {
                    title: vRoot.$t("reportForm.zzTimes"),
                    key: 'zzTimes'
                },
                {
                    title: vRoot.$t("reportForm.fzTimes"),
                    key: 'fzTimes'
                },
                {
                    title: vRoot.$t("reportForm.tzTimes"),
                    key: 'tzTimes'
                },
                {
                    title: vRoot.$t("reportForm.count"),
                    key: 'count'
                },
            ],
            allRotateTableData: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                { title: vRoot.$t("alarm.devName"), key: 'deviceName', width: 160 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 160 },
                { title: vRoot.$t("reportForm.status"), key: 'accStatus', width: 100 },
                { title: vRoot.$t("reportForm.startDate"), key: 'startDate', width: 180 },
                { title: vRoot.$t("reportForm.endDate"), key: 'endDate', width: 180 },
                {
                    title: vRoot.$t("reportForm.address"),
                    width: 145,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.slat ? row.slat : null;
                        var lon = row.slon ? row.slon : null;
                        if (lat && lon) {
                            if (row.address == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.tableData[params.index].address = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.address,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, lon + "," + lat)
                                ]);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
                { title: vRoot.$t("reportForm.duration") + '(H)', key: 'duration' },
            ],
            tableData: [],
            deviceNamesArr: [],
            zzTimesArr: [],
            fzTimesArr: [],
            tzTimesArr: [],
        },
        methods: {
            exportData: function() {

                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.zzTimes"),
                            vRoot.$t("reportForm.fzTimes"),
                            vRoot.$t("reportForm.tzTimes"),
                            vRoot.$t("reportForm.count"),
                        ]
                    ];
                    this.allRotateTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.zzTimes);
                        itemArr.push(item.fzTimes);
                        itemArr.push(item.tzTimes);
                        itemArr.push(item.count);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.rotationStatistics"),
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                } else {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.status"),
                            vRoot.$t("reportForm.startDate"),
                            vRoot.$t("reportForm.endDate"),
                            vRoot.$t("reportForm.address"),
                            vRoot.$t("reportForm.duration") + '(H)',
                        ]
                    ];

                    var len = this.tableData.length - 1;
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];
                        var lat = item.slat ? item.slat : null;
                        var lon = item.slon ? item.slon : null;
                        var address = null;
                        if (lat && lon) {
                            address = LocalCacheMgr.getAddress(lon, lat)
                        }
                        if (address !== null) {
                            item.address = address;
                        } else {
                            item.address = lon + "-" + lat;
                        }

                        itemArr.push(index + 1);

                        if (len == index) {
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push(item.duration);
                        } else {
                            itemArr.push(item.deviceName);
                            itemArr.push(item.deviceid);
                            itemArr.push(item.accStatus);
                            itemArr.push(item.startDate);
                            itemArr.push(item.endDate);
                            itemArr.push(item.address);
                            itemArr.push(item.duration);
                        }

                        data.push(itemArr);
                    });


                    var options = {
                        title: (isZh ? '正反转细节-' : 'Rotate-details-') + editObject.deviceid,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                }

            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            onChange: function(value) {
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 415;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length) {
                    var me = this;
                    var url = myUrls.rotateReports();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                        if (resp.status == 0) {
                            if (resp.records && resp.records.length) {
                                me.tableData = [];
                                me.allRotateTableData = me.getAllRotateTableData(resp.records);
                            } else {
                                me.tableData = [];
                                me.allRotateTableData = [];
                                me.deviceNamesArr = [];
                                me.zzTimesArr = [];
                                me.fzTimesArr = [];
                                me.tzTimesArr = [];
                                me.$Message.error(me.$t("reportForm.noRecord"));
                            }
                        } else {
                            me.tableData = [];
                            me.allRotateTableData = [];
                            me.deviceNamesArr = [];
                            me.zzTimesArr = [];
                            me.fzTimesArr = [];
                            me.tzTimesArr = [];
                        }
                        if (me.activeTab != "tabTotal") {
                            me.onClickTab("tabTotal");
                        }
                        me.displayChart();
                    });
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            getAllRotateTableData: function(records) {
                var me = this;
                var allRotateTableData = [];
                var deviceNamesArr = [];
                var zzTimesArr = [];
                var fzTimesArr = [];
                var tzTimesArr = [];
                records.forEach(function(item, index) {
                    var Obj = {
                            index: index + 1,
                            deviceid: "\t" + item.deviceid,
                            devicename: vstore.state.deviceInfos[item.deviceid].devicename,
                            records: item.records,
                        },
                        count = 0,
                        zzTimes = 0,
                        fzTimes = 0,
                        tzTimes = 0;
                    item.records.forEach(function(record) {
                        if (record.rotatestate == 1) {
                            zzTimes += record.endtime - record.begintime;
                        }
                        if (record.rotatestate == 2) {
                            fzTimes += record.endtime - record.begintime;
                        }
                        if (record.rotatestate == 3) {
                            tzTimes += record.endtime - record.begintime;
                        }
                        count++;
                    });
                    Obj.zzTimes = (zzTimes / 1000 / 3600).toFixed(2);
                    Obj.fzTimes = (fzTimes / 1000 / 3600).toFixed(2);
                    Obj.tzTimes = (tzTimes / 1000 / 3600).toFixed(2);
                    Obj.count = count;
                    deviceNamesArr.push(Obj.devicename);
                    zzTimesArr.push((zzTimes / 1000 / 60).toFixed(2));
                    fzTimesArr.push((fzTimes / 1000 / 60).toFixed(2));
                    tzTimesArr.push((tzTimes / 1000 / 60).toFixed(2));
                    allRotateTableData.push(Obj);
                });
                if (deviceNamesArr.length) {
                    this.deviceNamesArr = deviceNamesArr;
                    this.zzTimesArr = zzTimesArr;
                    this.fzTimesArr = fzTimesArr;
                    this.tzTimesArr = tzTimesArr;
                }
                return allRotateTableData;
            },
            getRotateDetailTableData: function(records) {
                var newRecords = [],
                    me = this;
                var zzTimes = 0;
                var fzTimes = 0;
                var tzTimes = 0;
                records.sort(function(a, b) {
                    return a.begintime - b.begintime;
                });
                records.forEach(function(item, index) {
                    var deviceName = vstore.state.deviceInfos[item.deviceid].devicename;
                    var duration = item.endtime - item.begintime;
                    var durationStr = (duration / 1000 / 3600).toFixed(2);;
                    var status = "";
                    var slon = item.slon.toFixed(5);
                    var slat = item.slat.toFixed(5);
                    var address = LocalCacheMgr.getAddress(slon, slat);
                    if (item.rotatestate == 1) {
                        status = me.$t("reportForm.zz");
                        zzTimes += duration;
                    } else if (item.rotatestate == 2) {
                        status = me.$t("reportForm.fz");
                        fzTimes += duration;
                    } else if (item.rotatestate == 3) {
                        tzTimes += duration;
                        status = me.$t("reportForm.tz");
                    }
                    newRecords.push({
                        index: index + 1,
                        deviceid: item.deviceid,
                        deviceName: deviceName,
                        startDate: DateFormat.longToLocalDateTimeStr(item.begintime),
                        endDate: DateFormat.longToLocalDateTimeStr(item.endtime),
                        accStatus: status,
                        address: address,
                        duration: durationStr,
                        slon: slon,
                        slat: slat,
                    });
                });
                newRecords.push({
                    duration: me.$t("reportForm.zz") + ':' + (zzTimes / 1000 / 3600).toFixed(2) + ',' + me.$t("reportForm.fz") + ':' + (fzTimes / 1000 / 3600).toFixed(2) + ',' + me.$t("reportForm.tz") + ':' + (tzTimes / 1000 / 3600).toFixed(2)
                })
                me.tableData = newRecords;
            },
            displayChart: function() {
                var barChartOtion = this.getChartOption();
                this.barChartJourney.setOption(barChartOtion, true);
            },
            getChartOption: function() {
                var dw_hour = this.$t("reportForm.h");
                var dw_min = this.$t("reportForm.m");
                var car = this.$t("alarm.devName");
                var zz = this.$t("reportForm.zz");
                var fz = this.$t("reportForm.fz");
                var tz = this.$t("reportForm.tz");
                //加载
                option = {
                    tooltip: {
                        show: true,
                        trigger: 'axis',
                        formatter: function(v) {
                            var zStr = "";
                            var fStr = "";
                            var tStr = "";
                            if (v.length == 1) {
                                var item1 = v[0];
                                if (item1.seriesIndex == 0) {
                                    if (v[0].value > 60) {
                                        zStr = parseInt(v[0].value / 60) + dw_hour + (v[0].value % 60).toFixed(2) + dw_min;
                                    } else if (v[0] && v[0].value % 60 == 0 && v[0].value != 0) {
                                        zStr = parseInt(v[0].value / 60) + dw_hour;
                                    } else {
                                        zStr = v[0].value + dw_min;
                                    }
                                    return car + ': ' + v[0].name + '</br>' +
                                        zz + ': ' + zStr + '</br>';
                                } else if (item1.seriesIndex == 1) {
                                    if (v[0].value > 60) {
                                        fStr = parseInt(v[0].value / 60) + dw_hour + (v[0].value % 60).toFixed(2) + dw_min;
                                    } else if (v[0] && v[0].value % 60 == 0 && v[0].value != 0) {
                                        fStr = parseInt(v[0].value / 60) + dw_hour;
                                    } else {
                                        fStr = v[0].value + dw_min;
                                    }
                                    return car + ': ' + v[0].name + '</br>' +
                                        fz + ': ' + fStr + '</br>';

                                } else if (item1.seriesIndex == 2) {
                                    if (v[0].value > 60) {
                                        tStr = parseInt(v[0].value / 60) + dw_hour + (v[0].value % 60).toFixed(2) + dw_min;
                                    } else if (v[0] && v[0].value % 60 == 0 && v[0].value != 0) {
                                        tStr = parseInt(v[0].value / 60) + dw_hour;
                                    } else {
                                        tStr = v[0].value + dw_min;
                                    }
                                    return car + ': ' + v[0].name + '</br>' +
                                        tz + ': ' + tStr;
                                }
                            } else if (v.length == 2) {
                                var item1 = v[0];
                                var item2 = v[1];
                                if (item1.seriesIndex == 0) {
                                    if (item1.value > 60) {
                                        zStr = parseInt(item1.value / 60) + dw_hour + (item1.value % 60).toFixed(2) + dw_min;
                                    } else if (item1 && item1.value % 60 == 0 && item1.value != 0) {
                                        zStr = parseInt(item1.value / 60) + dw_hour;
                                    } else {
                                        zStr = item1.value + dw_min;
                                    }
                                } else if (item1.seriesIndex == 1) {
                                    if (item1.value > 60) {
                                        fStr = parseInt(item1.value / 60) + dw_hour + (item1.value % 60).toFixed(2) + dw_min;
                                    } else if (item1 && item1.value % 60 == 0 && item1.value != 0) {
                                        fStr = parseInt(item1.value / 60) + dw_hour;
                                    } else {
                                        fStr = item1.value + dw_min;
                                    }
                                } else if (item1.seriesIndex == 2) {
                                    if (item1.value > 60) {
                                        tStr = parseInt(item1.value / 60) + dw_hour + (item1.value % 60).toFixed(2) + dw_min;
                                    } else if (item1 && item1.value % 60 == 0 && item1.value != 0) {
                                        tStr = parseInt(item1.value / 60) + dw_hour;
                                    } else {
                                        tStr = item1.value + dw_min;
                                    }
                                }
                                if (item2.seriesIndex == 0) {
                                    if (item2.value > 60) {
                                        zStr = parseInt(item2.value / 60) + dw_hour + (item2.value % 60).toFixed(2) + dw_min;
                                    } else if (item2 && item2.value % 60 == 0 && item2.value != 0) {
                                        zStr = parseInt(item2.value / 60) + dw_hour;
                                    } else {
                                        zStr = item2.value + dw_min;
                                    }
                                } else if (item2.seriesIndex == 1) {
                                    if (item2.value > 60) {
                                        fStr = parseInt(item2.value / 60) + dw_hour + (item2.value % 60).toFixed(2) + dw_min;
                                    } else if (item2 && item2.value % 60 == 0 && item2.value != 0) {
                                        fStr = parseInt(item2.value / 60) + dw_hour;
                                    } else {
                                        fStr = item2.value + dw_min;
                                    }
                                } else if (item2.seriesIndex == 2) {
                                    if (item2.value > 60) {
                                        tStr = parseInt(item2.value / 60) + dw_hour + (item2.value % 60).toFixed(2) + dw_min;
                                    } else if (item2 && item2.value % 60 == 0 && item2.value != 0) {
                                        tStr = parseInt(item2.value / 60) + dw_hour;
                                    } else {
                                        tStr = item2.value + dw_min;
                                    }
                                }

                                if (zStr === "") {
                                    return car + ': ' + v[0].name + '</br>' +
                                        fz + ': ' + fStr + '</br>' +
                                        tz + ': ' + tStr;
                                }
                                if (fStr === "") {
                                    return car + ': ' + v[0].name + '</br>' +
                                        zz + ': ' + zStr + '</br>' +
                                        tz + ': ' + tStr;
                                }
                                if (tStr === "") {
                                    return car + ': ' + v[0].name + '</br>' +
                                        zz + ': ' + zStr + '</br>' +
                                        fz + ': ' + fStr + '</br>';
                                }
                            } else if (v.length == 3) {
                                if (v[0].value > 60) {
                                    zStr = parseInt(v[0].value / 60) + dw_hour + (v[0].value % 60).toFixed(2) + dw_min;
                                } else if (v[0] && v[0].value % 60 == 0 && v[0].value != 0) {
                                    zStr = parseInt(v[0].value / 60) + dw_hour;
                                } else {
                                    zStr = v[0].value + dw_min;
                                }
                                if (v[1] && v[1].value > 60) {
                                    fStr = parseInt(v[1].value / 60) + dw_hour + (v[1].value % 60).toFixed(2) + dw_min;
                                } else if (v[1] && v[1].value % 60 == 0 && v[1].value != 0) {
                                    fStr = parseInt(v[1].value / 60) + dw_hour;
                                } else {
                                    fStr = v[1].value + dw_min;
                                }
                                if (v[2] && v[2].value > 60) {
                                    tStr = parseInt(v[2].value / 60) + dw_hour + (v[2].value % 60).toFixed(2) + dw_min;
                                } else if (v[2] && v[2].value % 60 == 0 && v[2].value != 0) {
                                    tStr = parseInt(v[2].value / 60) + dw_hour;
                                } else {
                                    tStr = v[2].value + dw_min;
                                }
                                return car + ': ' + v[0].name + '</br>' +
                                    zz + ': ' + zStr + '</br>' +
                                    fz + ': ' + fStr + '</br>' +
                                    tz + ': ' + tStr;
                            }

                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [zz, fz, tz],
                        y: 13,
                        x: 'center'
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14,
                        y: 'top',
                        x: 'right'
                    },
                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        //boundaryGap : false,
                        axisLabel: {
                            show: true,
                            interval: 0, // {number}
                            rotate: 0,
                            margin: 8,
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        data: this.deviceNamesArr
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }],
                    series: [{
                            name: zz,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                            },
                            data: this.zzTimesArr
                        },
                        {
                            name: fz,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                            },
                            data: this.fzTimesArr
                        },
                        {
                            name: tz,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '14',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                            },
                            data: this.tzTimesArr
                        }
                    ]
                };
                return option;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;

            this.queryDevicesTree();
            this.barChartJourney = echarts.init(document.getElementById('barContainer'));
            this.displayChart();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
                me.barChartJourney.resize();
            }
        }
    })

}

function speedingReport(groupslist) {
    vueInstanse = new Vue({
        el: '#speeding-report',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            activeTab: 'tabTotal',
            mapModal: false,
            mapType: utils.getMapType(),
            mapInstance: null,
            markerIns: null,
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            allAccColumns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 160,
                    render: function(h, params) {
                        var records = params.row.records;
                        return h('span', {
                            on: {
                                click: function() {

                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getSpeedingDetailTableData(records);
                                    editObject = params.row;
                                    if (records.length) {
                                        vueInstanse.isSpin = true;
                                        var row = deepClone(records[0]);
                                        row.startDate = DateFormat.longToLocalDateTimeStr(row.begintime);
                                        row.endDate = DateFormat.longToLocalDateTimeStr(row.endtime);
                                        vueInstanse.querySingleDevTracks('charts', row);
                                    }

                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.speedingDetails") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                    width: 160,
                },
                {
                    title: vRoot.$t("reportForm.speedingDuration"),
                    key: 'duration'
                },
                {
                    title: vRoot.$t("reportForm.speedingMileage"),
                    key: 'distance'
                },
                {
                    title: vRoot.$t("reportForm.speedingCount"),
                    key: 'count'
                },
                {
                    title: vRoot.$t("reportForm.maxSpeed") + '(km/h)',
                    key: 'maxSpeed'
                },
                {
                    title: vRoot.$t("reportForm.minSpeed") + '(km/h)',
                    key: 'minSpeed'
                }
            ],
            allRotateTableData: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                { title: vRoot.$t("alarm.devName"), key: 'deviceName' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid' },
                { title: vRoot.$t("reportForm.startDate"), key: 'startDate' },
                { title: vRoot.$t("reportForm.endDate"), key: 'endDate' },
                { title: vRoot.$t("reportForm.duration") + '(H)', key: 'duration' },
                { title: vRoot.$t("reportForm.maxSpeed") + '(km/h)', width: 120, key: 'maxSpeed' },
                { title: vRoot.$t("reportForm.minSpeed") + '(km/h)', width: 120, key: 'minSpeed' },
                {
                    title: vRoot.$t("reportForm.address"),
                    width: 145,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.slat ? row.slat : null;
                        var lon = row.slon ? row.slon : null;
                        if (lat && lon) {
                            if (row.address == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.tableData[params.index].address = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.address,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, lon + "," + lat)
                                ]);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
                {
                    title: vRoot.$t("alarm.action"),
                    render: function(h, params) {
                        return h(
                            'div', {}, [
                                h('Button', {
                                    props: {
                                        size: 'small',
                                    },
                                    on: {
                                        click: function(e) {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            vueInstanse.isSpin = true;
                                            vueInstanse.querySingleDevTracks('map', params.row);
                                        }
                                    }
                                }, isZh ? "显示轨迹" : "Show track"),
                            ]
                        )
                    },
                },
            ],
            tableData: [],
            limitspeed: '90',
            trackDetailModal: false,
            isZh: isZh
        },
        methods: {
            onRowClick: function(row) {
                this.isSpin = true;
                this.querySingleDevTracks('charts', row);
            },
            querySingleDevTracks: function(type, row) {
                var me = this;
                var url = myUrls.queryTracks();
                var data = {
                    deviceid: row.deviceid,
                    begintime: row.startDate,
                    endtime: row.endDate,
                    timezone: timeDifference
                };

                utils.sendAjax(url, data, function(resp) {
                        me.isSpin = false;
                        if (resp.status == 0) {
                            var records = resp.records;
                            if (records && records.length) {
                                if (type == 'map') {
                                    utils.markersAndLineLayerToMap(me, records);
                                    me.trackDetailModal = true;
                                } else {
                                    var distance = []; //总里程;
                                    var recvtime = []; //时间
                                    var veo = []; //速度
                                    me.disMin = 0;

                                    records.forEach(function(item, index) {
                                        item.totaldistance = (item.totaldistance / 1000).toFixed(2)
                                        if (index == 0) {
                                            me.disMin = item.totaldistance
                                        }

                                        recvtime.push(DateFormat.longToLocalDateTimeStr(item.updatetime));
                                        veo.push((item.speed / 1000).toFixed(2));
                                        distance.push(item.totaldistance);
                                    });
                                    me.distance = distance;
                                    me.recvtime = recvtime;
                                    me.veo = veo;
                                    me.speedChart.setOption(me.getSpeedChartsOption(), true);
                                }
                            } else {
                                me.$Message.error(isZh ? '没有轨迹' : 'No Data');
                            }
                        }
                    },
                    function() {
                        me.isSpin = false;
                    });
            },
            getBdPoints: function(records) {
                var points = [];
                records.forEach(function(item) {
                    var lon_lat = wgs84tobd09(item.callon, item.callat);
                    points.push(new BMap.Point(lon_lat[0], lon_lat[1]));
                });
                return points;
            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('spedding-map');
            },
            exportData: function() {

                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.speedingDuration"),
                            vRoot.$t("reportForm.speedingMileage"),
                            vRoot.$t("reportForm.speedingCount"),
                            vRoot.$t("reportForm.maxSpeed") + '(km/h)',
                            vRoot.$t("reportForm.minSpeed") + '(km/h)',
                        ]
                    ]

                    this.allRotateTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.duration);
                        itemArr.push(item.distance);
                        itemArr.push(item.count);
                        itemArr.push(item.maxSpeed);
                        itemArr.push(item.minSpeed);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.speedingStatistics'),
                        data: data,
                        dateRange: this.queryDateRange,
                    }



                } else {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("reportForm.startDate"),
                            vRoot.$t("reportForm.endDate"),
                            vRoot.$t("reportForm.duration"),
                            vRoot.$t("reportForm.maxSpeed") + '(km/h)',
                            vRoot.$t("reportForm.minSpeed") + '(km/h)',
                            vRoot.$t("reportForm.address"),
                        ]
                    ]

                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];

                        itemArr.push(index + 1);
                        itemArr.push(item.deviceName);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.startDate);
                        itemArr.push(item.endDate);
                        itemArr.push(item.duration);
                        itemArr.push(item.maxSpeed);
                        itemArr.push(item.minSpeed);
                        itemArr.push(item.address);

                        data.push(itemArr);
                    });


                    var options = {
                        title: vRoot.$t('reportForm.speedingDetails') + ' - ' + editObject.deviceid,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                }
                new XlsxCls(options).exportExcel();
            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            onChange: function(value) {
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 415;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length) {
                    var me = this;
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids,
                        limitspeed: 0
                    }
                    me.reportOverSpeeds(data);
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            onClickSoftwareQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length) {
                    var me = this;
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids,
                        limitspeed: Number(this.limitspeed)
                    }
                    me.reportOverSpeeds(data);
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            reportOverSpeeds: function(data) {
                var me = this;
                me.loading = true;
                utils.sendAjax(myUrls.reportOverSpeeds(), data, function(resp) {
                    me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                    me.loading = false;
                    if (resp.status == 0) {
                        if (resp.records && resp.records.length) {
                            me.tableData = [];
                            me.allRotateTableData = me.getAllRotateTableData(resp.records);
                        } else {
                            me.tableData = [];
                            me.allRotateTableData = [];
                            me.deviceNamesArr = [];
                            me.countArr = [];
                            me.$Message.error(vRoot.$t('reportForm.noRecord'));
                        }
                    } else {
                        me.tableData = [];
                        me.allRotateTableData = [];
                        me.deviceNamesArr = [];
                        me.countArr = [];
                    }
                    if (me.activeTab != "tabTotal") {
                        me.onClickTab("tabTotal");
                    }
                    me.displayChart();
                });
            },
            getAllRotateTableData: function(records) {
                var me = this;
                var allRotateTableData = [];
                var deviceNamesArr = [];
                var countArr = [];
                records.forEach(function(item, index) {
                    var Obj = {
                            index: index + 1,
                            deviceid: "\t" + item.deviceid,
                            devicename: vstore.state.deviceInfos[item.deviceid].devicename,
                            records: item.records,
                        },
                        count = 0,
                        duration = 0,
                        distance = 0,
                        maxSpeed = '-',
                        minSpeed = '-';
                    item.records.sort(function(a, b) {
                        return b.endtime - a.endtime;
                    });
                    item.records.forEach(function(record) {
                        duration += record.endtime - record.begintime;
                        distance += record.edistance - record.sdistance;
                        maxSpeed === '-' && (maxSpeed = record.maxspeed);
                        minSpeed === '-' && (minSpeed = record.minspeed);
                        if (record.maxspeed > maxSpeed) {
                            maxSpeed = record.maxspeed;
                        }
                        if (record.minspeed < minSpeed) {
                            minSpeed = record.minspeed;
                        }
                        count++;

                    });
                    Obj.maxSpeed = maxSpeed === '-' ? '-' : (maxSpeed / 1000).toFixed(2);
                    Obj.minSpeed = minSpeed === '-' ? '-' : (minSpeed / 1000).toFixed(2);
                    Obj.count = count;
                    Obj.duration = (duration / 1000 / 3600).toFixed(2);
                    Obj.distance = (distance / 1000).toFixed(2) + 'km';
                    deviceNamesArr.push(Obj.devicename);
                    countArr.push(count);
                    allRotateTableData.push(Obj);
                });
                if (deviceNamesArr.length) {
                    this.deviceNamesArr = deviceNamesArr;
                    this.countArr = countArr;
                }
                return allRotateTableData;
            },
            getSpeedingDetailTableData: function(records) {
                var newRecords = [],
                    me = this;
                console.log(records);
                records.forEach(function(item, index) {

                    var deviceName = vstore.state.deviceInfos[item.deviceid].devicename;
                    var duration = item.endtime - item.begintime;
                    var durationStr = (duration / 1000 / 3600).toFixed(2);;
                    var status = "";
                    var slon = item.slon.toFixed(5);
                    var slat = item.slat.toFixed(5);
                    var address = LocalCacheMgr.getAddress(slon, slat);
                    newRecords.push({
                        index: index + 1,
                        deviceid: item.deviceid,
                        deviceName: deviceName,
                        startDate: DateFormat.longToLocalDateTimeStr(item.begintime),
                        endDate: DateFormat.longToLocalDateTimeStr(item.endtime),
                        accStatus: status,
                        address: address,
                        duration: durationStr,
                        slon: slon,
                        slat: slat,
                        maxSpeed: (item.maxspeed / 1000).toFixed(2),
                        minSpeed: (item.minspeed / 1000).toFixed(2)
                    });
                });

                me.tableData = newRecords;
            },
            displayChart: function() {
                var barChartOtion = this.getChartOption();
                this.barChartJourney.setOption(barChartOtion, true);
            },
            getChartOption: function() {
                var car = isZh ? '车辆' : 'vehicle';
                var cs = this.$t('reportForm.speedingCount');
                //加载
                option = {
                    tooltip: {
                        show: true,
                        trigger: 'axis',

                    },
                    legend: {
                        data: [cs],
                        y: 13,
                        x: 'center'
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14,
                        y: 'top',
                        x: 'right'
                    },
                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        //boundaryGap : false,
                        axisLabel: {
                            show: true,
                            interval: 0, // {number}
                            rotate: 0,
                            margin: 8,
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        data: this.deviceNamesArr
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }],
                    series: [{
                        name: cs,
                        type: 'bar',
                        itemStyle: {
                            //默认样式
                            normal: {
                                label: {
                                    show: true,
                                    textStyle: {
                                        fontSize: '12',
                                        fontFamily: '微软雅黑',
                                        fontWeight: 'bold'
                                    }
                                }
                            }
                        },
                        data: this.countArr
                    }]
                };
                return option;
            },
            getSpeedChartsOption: function() {
                var speed = this.$t('reportForm.speed');
                var dis = this.$t('reportForm.mileage');
                var time = this.$t('reportForm.date');
                var option = {
                    title: {
                        text: time + (isZh ? '/超速' : '/speeding'),
                        x: 'center',
                        textStyle: {
                            fontSize: 12,
                            fontWeight: 'bolder',
                            color: '#333'
                        }
                    },
                    grid: {
                        x: 50,
                        y: 40,
                        x2: 50,
                        y2: 40
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName != time) {
                                    // data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    if (v[i].seriesName == dis) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [dis, speed],
                        //selected: {
                        //    '里程' : false
                        // },
                        x: 'left'
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: {
                                show: true,
                                type: ['line', 'bar']
                            },
                            restore: {
                                show: true
                            },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        //fillerColor:'rgb(244,129,38,0.8)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: speed,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: dis,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                        name: time,
                        type: 'line',
                        symbol: 'none',
                        yAxisIndex: 1,
                        color: '#F0805A',
                        smooth: true,
                        data: this.recvtime
                    }, {
                        name: dis,
                        type: 'line',
                        symbol: 'none',
                        yAxisIndex: 1,
                        color: '#3CB371',
                        smooth: true,
                        data: this.distance
                    }, {
                        name: speed,
                        type: 'line',
                        symbol: 'none',
                        yAxisIndex: 0,
                        smooth: true,
                        color: '#4876FF',
                        data: this.veo
                    }]
                };
                return option;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            this.queryDevicesTree();
            this.initMap();
            this.barChartJourney = echarts.init(document.getElementById('barContainer'));
            this.displayChart();
            this.deviceNamesArr = [];
            this.countArr = [];
            this.distance = [];
            this.recvtime = [];
            this.veo = [];
            this.speedChart = echarts.init(document.getElementById('spedding-chart'));
            this.speedChart.setOption(this.getSpeedChartsOption(), true);
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
                me.barChartJourney.resize();
                me.speedChart.resize();
            }
        }
    })
}


function devRecords(groupslist) {
    vueInstanse = new Vue({
        el: '#dev-records',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            tableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            isShowMatchDev: true,
            columns: [
                { type: 'index', width: 60, align: 'center' },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 200 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 200 },
                { title: vRoot.$t("reportForm.date"), key: 'updatetimeStr', width: 200 },
                {
                    title: vRoot.$t("reportForm.download"),
                    render: function(h, data) {
                        return h(
                            "a", {
                                attrs: {
                                    download: true,
                                    target: "_blank",
                                    href: data.row.url
                                }
                            },
                            vRoot.$t("reportForm.download"))
                    },
                    width: 160,
                },
                {
                    title: vRoot.$t("monitor.media"),
                    render: function(h, data) {
                        return h(
                            "audio", {
                                style: {
                                    marginTop: "5px"
                                },
                                attrs: {
                                    controls: "controls",
                                    src: data.row.url
                                }
                            }
                        )
                    }
                },
            ],
            tableData: []
        },
        methods: {
            exportData: function() {
                var tableData = deepClone(this.tableData);
                var columns = deepClone(this.columns);
                columns.pop();
                columns.pop();
                columns.push({
                    title: vRoot.$t("reportForm.download"),
                    key: 'url',
                })
                tableData.forEach(function(item) {
                    if (item.deviceName) {
                        item.devicename = "\t" + item.devicename;
                        item.deviceid = "\t" + item.deviceid;
                        item.updatetimeStr = "\t" + item.updatetimeStr;
                    }
                });
                this.$refs.table.exportCsv({
                    filename: vRoot.$t('reportForm.voiceReport') + '-' + this.queryDeviceId,
                    original: false,
                    columns: columns,
                    data: tableData
                });
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") { return };
                var me = this;
                var url = myUrls.reportAudio();
                var data = {
                    deviceid: this.queryDeviceId
                }
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status === 0) {
                        var records = resp.records;
                        var tableData = [];
                        records.forEach(function(record) {
                            tableData.push({
                                devicename: me.sosoValue,
                                deviceid: me.queryDeviceId,
                                updatetimeStr: DateFormat.longToLocalDateTimeStr(record.updatetime),
                                url: record.url
                            })
                        });
                        me.tableData = tableData;
                        if (tableData.length === 0) {
                            vRoot.$t("reportForm.noRecord");
                        }
                    }
                })
            },
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    });
}


function messageRecords(groupslist) {
    vueInstanse = new Vue({
        el: '#messageRecords',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            isShowCard: false,
            tableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            isShowMatchDev: true,
            startDate: new Date(),
            columns: [
                { title: vRoot.$t("reportForm.sn"), key: 'sn', width: 80, "sortable": true, fixed: 'left' },
                { title: vRoot.$t("reportForm.messagetype"), key: 'messagetype', width: 110 },
                { title: vRoot.$t("reportForm.typedescr"), key: 'typedescr', width: 120 },
                { title: vRoot.$t("reportForm.status"), key: 'status', width: 80 },
                { title: vRoot.$t("reportForm.strstatus"), key: isZh ? 'strstatus' : 'strstatusen', width: 220 },
                { title: vRoot.$t("reportForm.stralarm"), key: 'stralarm', width: 120 },
                { title: vRoot.$t("reportForm.updatetimeStr"), key: 'updatetimeStr', width: 160 },
                { title: vRoot.$t("reportForm.arrivedtimeStr"), key: 'arrivedtimeStr', width: 160 },
                { title: vRoot.$t("reportForm.reportmodeStr"), key: 'reportmodeStr', width: 120 },
                { title: vRoot.$t("reportForm.reissue"), key: 'reissue', width: 80 },
                { title: vRoot.$t("reportForm.callat"), key: 'callat', width: 120 },
                { title: vRoot.$t("reportForm.callon"), key: 'callon', width: 120 },
                { title: vRoot.$t("reportForm.radius"), key: 'radius', width: 80 },
                { title: vRoot.$t("reportForm.speed"), key: 'speed', width: 80 },
                { title: vRoot.$t("reportForm.recorderspeed"), key: 'recorderspeed', width: 120 },
                { title: vRoot.$t("reportForm.totaldistance"), key: 'totaldistance', width: 120 },
                { title: vRoot.$t("reportForm.altitude") + '(M)', key: 'altitude', width: 100 },
                { title: vRoot.$t("reportForm.course"), key: 'course', width: 100 },
                { title: vRoot.$t("reportForm.gotsrc"), key: 'gotsrc', width: 100 },
                { title: vRoot.$t("reportForm.rxlevel"), key: 'rxlevel', width: 100 },
            ],
            tableData: [],
            currentIndex: 1,
            total: 0,
            contentString: "",
            filterStr: '',
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("reportForm.sn"),
                        vRoot.$t("reportForm.messagetype"),
                        vRoot.$t("reportForm.typedescr"),
                        vRoot.$t("reportForm.status"),
                        vRoot.$t("reportForm.strstatus"),
                        vRoot.$t("reportForm.stralarm"),
                        vRoot.$t("reportForm.updatetimeStr"),
                        vRoot.$t("reportForm.arrivedtimeStr"),
                        vRoot.$t("reportForm.reportmodeStr"),
                        vRoot.$t("reportForm.reissue"),
                        vRoot.$t("reportForm.callat"),
                        vRoot.$t("reportForm.callon"),
                        vRoot.$t("reportForm.radius"),
                        vRoot.$t("reportForm.speed"),
                        vRoot.$t("reportForm.recorderspeed"),
                        vRoot.$t("reportForm.totaldistance"),
                        vRoot.$t("reportForm.altitude") + '(M)',
                        vRoot.$t("reportForm.course"),
                        vRoot.$t("reportForm.gotsrc"),
                        vRoot.$t("reportForm.rxlevel"),
                    ]
                ];

                this.data.forEach(function(item, index) {
                    var itemArr = [];

                    itemArr.push(index + 1);
                    itemArr.push(item.sn);
                    itemArr.push(item.messagetype);
                    itemArr.push(item.typedescr);
                    itemArr.push(item.status);
                    itemArr.push(isZh ? item.strstatus : item.strstatusen);
                    itemArr.push(item.stralarm);
                    itemArr.push(item.updatetimeStr);
                    itemArr.push(item.arrivedtimeStr);
                    itemArr.push(item.reportmodeStr);
                    itemArr.push(item.reissue);
                    itemArr.push(item.callat);
                    itemArr.push(item.callon);
                    itemArr.push(item.radius);
                    itemArr.push(item.speed);
                    itemArr.push(item.recorderspeed);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.altitude);
                    itemArr.push(item.course);
                    itemArr.push(item.gotsrc);
                    itemArr.push(item.rxlevel);

                    data.push(itemArr);
                });
                var options = {
                    title: this.queryDeviceId + (isZh ? '-报文' : '-Records'),
                    data: data,
                    dateRange: false,
                }
                new XlsxCls(options).exportExcel();

            },
            charts: function(title) {
                var option = {
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'right',
                    },
                    grid: {
                        top: 5,
                        left: 20,
                        right: 5,
                        bottom: 5,
                    },
                    // dataZoom: [{
                    //     show: true,
                    //     realtime: true,
                    //     start: 1,
                    //     end: 10000
                    // }],
                    series: [{
                        type: 'pie',
                        radius: '70%',
                        data: this.seriesData,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }]
                };;
                this.chartsIns.setOption(option, true);
            },
            onRowClick: function(row) {
                var me = this;
                this.isShowCard = true;
                this.queryTrackDetail(row, function(resp) {
                    if (resp.track) {
                        me.contentString = JSON.stringify(resp.track);
                    } else {
                        vm.$Message.error(me.$t("reportForm.noRecord"));
                    }
                });
            },
            queryTrackDetail: function(row, callback) {
                var data = {
                    deviceid: this.queryDeviceId,
                    updatetime: row.updatetime,
                    trackid: row.trackid
                }
                var url = myUrls.queryTrackDetail();
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        callback(resp);
                    }
                })
            },
            closeCard: function() {
                this.isShowCard = false;
            },
            filterTypeDesc: function() {
                if (this.filterStr) {
                    var that = this;
                    var filterArr = [];
                    for (var i = 0; i < this.data.length; i++) {
                        var item = this.data[i];
                        if ((item.typedescr && item.typedescr.indexOf(that.filterStr) != -1) || item.strstatus.indexOf(that.filterStr) != -1 || item.stralarm.indexOf(that.filterStr) != -1 || item.messagetype.indexOf(that.filterStr) != -1) {
                            filterArr.push(item);
                            if (filterArr.length > 80) {
                                break;
                            }
                        }
                    }
                    this.tableData = filterArr;
                };
            },
            onChange: function(index) {
                this.isShowCard = false;
                this.currentIndex = index;
                this.tableData = this.data.slice((index - 1) * 20, (index - 1) * 20 + 20);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 380 - 30;
            },
            nextDay: function() {
                this.startDate = new Date(this.startDate.getTime() + this.dayTime);
            },
            prevDay: function() {
                this.startDate = new Date(this.startDate.getTime() - this.dayTime);

            },
            requestTracks: function(callback) {
                if (!this.queryDeviceId) return;
                this.loading = true;
                var url = myUrls.queryTracksDetail(),
                    me = this;
                var startTimeStr = DateFormat.format(this.startDate, 'yyyy-MM-dd') + ' 00:00:00';
                var endTimeStr = DateFormat.format(this.startDate, 'yyyy-MM-dd') + ' 23:59:00';
                var data = {
                    deviceid: this.queryDeviceId,
                    lbs: 1,
                    timezone: timeDifference,
                    interval: -1,
                    begintime: startTimeStr,
                    endtime: endTimeStr
                };
                utils.sendAjax(url, data, function(resp) {
                    me.loading = false;
                    callback(resp)
                });
            },
            onClickQuery: function() {
                var me = this;

                this.requestTracks(function(resp) {
                    if (resp.status == 0 && resp.records) {
                        var seriesObj = {};
                        var recvtime = [];
                        var speeds = [];
                        var mileages = [];
                        var status = [];
                        var reissues = [];
                        var records = resp.records;
                        records.forEach(function(record) {
                            var type = null;
                            var copyType = null;
                            var status = record.status;
                            var messageType = record.messagetype;
                            var paddedZeroMessageType = "0x" + utils.padPreZero(parseInt(record.messagetype, 10).toString(16), 4);
                            if (messageType == 0x200) {
                                var isLocated = (status & 0x4) == 0x4;
                                if (isLocated) {
                                    type = paddedZeroMessageType + '-1(' + record.messagetype + ')';
                                    copyType = paddedZeroMessageType + '-1(' + record.typedescr + ')';
                                } else {
                                    type = paddedZeroMessageType + '-0(' + record.messagetype + ')';
                                    copyType = paddedZeroMessageType + '-1(' + record.typedescr + ')';
                                }
                            } else {
                                type = paddedZeroMessageType + '(' + record.messagetype + ')';
                                copyType = paddedZeroMessageType + '(' + record.typedescr + ')';
                            }


                            record.messagetype = type;
                            record.reportmodeStr = reportmodeStr = getReportModeStr(record.reportmode);
                            record.updatetimeStr = '\t' + DateFormat.longToLocalDateTimeStr(record.updatetime);
                            record.arrivedtimeStr = '\t' + DateFormat.longToLocalDateTimeStr(record.arrivedtime);

                            if (seriesObj[copyType] == undefined) {
                                seriesObj[copyType] = {
                                    name: copyType,
                                    value: 1
                                };
                            } else {
                                seriesObj[copyType].value++;
                            }
                        });
                        records.sort(function(a, b) {
                            return b.updatetime - a.updatetime;
                        });
                        var minMileage = 0;
                        if (records.length > 0) {
                            minMileage = records[records.length - 1].totaldistance;
                        }
                        records.forEach(function(item) {
                            recvtime.unshift(item.updatetimeStr);
                            speeds.unshift(Number((item.speed / 1000).toFixed(2)));
                            mileages.unshift(Number(((item.totaldistance - minMileage) / 1000).toFixed(2)));
                            status.unshift(isZh ? item.strstatus : item.strstatusen);
                            reissues.unshift(item.reissue == 0 ? '否' : '是');
                        });


                        me.seriesData = Object.values(seriesObj);
                        me.seriesData.sort(function(a, b) {
                            return b.value - a.value;
                        });
                        me.charts();
                        me.timeCharts(recvtime, speeds, mileages, status, reissues);
                        me.data = Object.freeze(records);
                        me.total = me.data.length;
                        me.tableData = me.data.slice(0, 20);
                        me.currentIndex = 1;
                    } else {
                        me.total = 0;
                        me.data = [];
                        me.tableData = [];
                    }
                })
            },
            timeCharts: function(recvtime, speeds, mileages, status, reissues) {
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var weight = vRoot.$t('reportForm.weight');
                var statusStr = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t("reportForm.reissue");
                var option = {
                    title: {
                        text: time,
                        x: 'center',
                        textStyle: {
                            fontSize: 12,
                            fontWeight: 'bolder',
                            color: '#333'
                        }
                    },
                    grid: {
                        x: 50,
                        y: 40,
                        x2: 50,
                        y2: 40,
                        bottom: 55
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName && v[i].seriesName != time) {
                                    if (v[i].seriesName == weight) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'kg<br/>';
                                    } else if (v[i].seriesName == dis) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else {
                                        data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis],
                        x: 'left'
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: recvtime
                    }],
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        bottom: 10
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    yAxis: [{
                        name: speed,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: dis,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: speeds
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: mileages
                        },
                        {
                            smooth: true,
                            name: statusStr,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: status
                        },
                        {
                            smooth: true,
                            name: reissue,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: reissues
                        }
                    ]
                };

                this.timeChartsIns.setOption(option);
            }
        },
        watch: {
            filterStr: function() {
                if (this.filterStr == '') {
                    this.tableData = this.data.slice((this.currentIndex - 1) * 20, (this.currentIndex - 1) * 20 + 20);
                }
            }
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.calcTableHeight();
            this.dayTime = 60 * 60 * 24 * 1000;
            this.seriesData = [];
            this.data = [];
            setTimeout(function() {
                me.timeChartsIns = echarts.init(document.getElementById('time_charts'));
                me.chartsIns = echarts.init(document.getElementById('msg_charts'));
                me.charts();
                me.timeCharts([], [], [], [], []);

                me.timeChartsIns.getZr().on('click', function(params) {
                    var pointInPixel = [params.offsetX, params.offsetY];
                    if (me.timeChartsIns.containPixel('grid', pointInPixel)) {
                        var tracks = me.data;
                        if (tracks.length) {
                            var xIndex = me.timeChartsIns.convertFromPixel({
                                seriesIndex: 0
                            }, [params.offsetX, params.offsetY])[0];

                            var currentIndex = Math.ceil((tracks.length - xIndex) / 20);
                            var rowIndex = (tracks.length - xIndex) % 20;
                            if (rowIndex == 0) {
                                rowIndex = 19;
                            } else {
                                rowIndex = rowIndex - 1;
                            }
                            me.onChange(currentIndex);
                            me.currentIndex = currentIndex;

                            setTimeout(function() {
                                me.$refs.table.$refs.tbody.clickCurrentRow(rowIndex);
                                var rowHeight = $('tr.ivu-table-row')[0].getBoundingClientRect().height
                                $('div.ivu-table-body').animate({
                                    scrollTop: (rowIndex * rowHeight) + 'px'
                                }, 300);
                            }, 500)
                        }
                    }
                });
            }, 300);
            window.onresize = function() {
                me.calcTableHeight();
            };
        },
    })
}


// 查询报警
function allAlarm(groupslist) {
    vueInstanse = new Vue({
        el: "#all-alarm",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            alarmModel: false,
            isZh: isZh,
            groupslist: [],
            alarmColumns: [
                { type: 'index', width: 60, align: 'center' },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                    width: 120,
                },
                {
                    title: vRoot.$t("reportForm.startAlarmDate"),
                    key: 'startalarmtimeStr',
                    width: 160
                },
                {
                    title: vRoot.$t("reportForm.lastAlarmDate"),
                    key: 'lastalarmtimeStr',
                    width: 160
                },
                {
                    title: vRoot.$t("reportForm.alarmInfo"),
                    key: isZh ? 'stralarm' : 'stralarmen',
                },
                {
                    title: vRoot.$t("reportForm.alarmCount"),
                    key: 'alarmcount',
                    width: 110
                },
                {
                    title: vRoot.$t("reportForm.isDispose"),
                    key: 'isdispose',
                    width: 100
                },
                {
                    title: vRoot.$t("reportForm.disposePerson"),
                    key: 'disposeperson',
                    width: 100,
                    render: function(h, params) {
                        var creater = params.row.disposeperson ? params.row.disposeperson : '-';
                        return h('Poptip', {
                            props: {
                                confirm: false,
                                // title: '上级信息',
                            },
                            style: {
                                marginRight: '5px',
                            },
                        }, [
                            h('Button', {
                                props: {
                                    type: 'info',
                                    size: 'small'
                                },
                                on: {
                                    click: function() {

                                        var url = myUrls.queryParents();
                                        var data = {
                                            currentuser: creater
                                        }
                                        utils.sendAjax(url, data, function(resp) {
                                            var createrrecords = [];
                                            var records = resp.records;
                                            records.forEach(function(item) {
                                                createrrecords.push(h('div', {}, item.username + '(' + utils.getUserTypeDesc(item.usertype) + ')'))
                                            });
                                            params.row.createrrecords = createrrecords;
                                        })
                                    }
                                }
                            }, creater),
                            h(
                                'div', {
                                    slot: 'content',
                                    attrs: {
                                        slot: "content"
                                    }
                                }, params.row.createrrecords
                            )
                        ]);
                    }
                },
            ],
            alarmData: [],
            tableHeight: 100,
            checkboxObj: {},
            alarmTypeList: deepClone(alarmTypeList),
            checkAll: true,
            searchValue: '',
            needalarmstr: '',
        },
        mixins: [treeMixin],
        watch: {
            searchValue: function(newVal) {
                if (newVal.length == 0) {
                    this.alarmTypeList.forEach(function(item) {
                        item.show = true;
                    });
                } else {
                    this.alarmTypeList.forEach(function(item) {
                        if (isZh) {
                            if (item.alarmname.indexOf(newVal) != -1) {
                                item.show = true;
                            } else {
                                item.show = false;
                            }
                        } else {
                            if (item.alarmnameen.indexOf(newVal) != -1) {
                                item.show = true;
                            } else {
                                item.show = false;
                            }
                        }

                    });
                }
            },
            alarmModel: function(newVal) {
                if (newVal) {
                    this.checkboxObj = deepClone(this.copyCheckboxObj);
                    var checkAll = true;

                    for (var key in this.checkboxObj) {
                        if (!this.checkboxObj[key]) {
                            checkAll = false;
                        }
                    }

                    this.checkAll = checkAll;
                }
            }
        },
        methods: {
            setForceAlarmClick: function() {
                this.copyCheckboxObj = deepClone(this.checkboxObj);
                var needalarmstr = '';
                for (var key in this.copyCheckboxObj) {
                    if (this.copyCheckboxObj[key]) {
                        needalarmstr += "1";
                    } else {
                        needalarmstr += "0";
                    }
                }
                this.needalarmstr = needalarmstr;
                this.alarmModel = false;
            },
            checkingSelectState: function() {
                var me = this;
                setTimeout(function() {
                    var isCheckAll = true;
                    for (var key in me.checkboxObj) {
                        if (!me.checkboxObj[key]) {
                            isCheckAll = false;
                            break;
                        }
                    }
                    // console.log('isCheckAll', isCheckAll);
                    me.checkAll = isCheckAll;
                }, 300)
            },
            onCheckAll: function() {
                var me = this;
                this.checkAll = !this.checkAll;
                for (var key in me.checkboxObj) {
                    // console.log('checkAll', this.checkAll);
                    me.checkboxObj[key] = this.checkAll;
                }
            },
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("reportForm.startAlarmDate"),
                        vRoot.$t("reportForm.lastAlarmDate"),
                        vRoot.$t("reportForm.alarmInfo"),
                        vRoot.$t("reportForm.alarmCount"),
                        vRoot.$t("reportForm.isDispose"),
                    ]
                ];
                this.alarmData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.startalarmtimeStr);
                    itemArr.push(item.lastalarmtimeStr);
                    itemArr.push(isZh ? item.stralarm : item.stralarmen);
                    itemArr.push(item.alarmcount);
                    itemArr.push(item.isdispose);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.allAlarm') + '-' + this.queryDeviceId,
                    data: data,
                    dateRange: false,
                }
                new XlsxCls(options).exportExcel();


            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            onClickQuery: function() {

                if (this.checkedDevice.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.loading = true;
                var needalarmstr = '';
                for (var i = 0; i < alarmTypeList.length; i++) {
                    needalarmstr += this.copyCheckboxObj[i] ? '1' : '0';
                }

                var url = myUrls.reportAlarm(),
                    self = this;
                var data = {
                    devices: [],
                    needalarm: needalarmstr
                }
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            data.devices.push(group.deviceid);
                        }
                    }
                });
                if (data.devices.length === 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }


                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        var alarmRecords = [];
                        if (resp.alarmrecords && resp.alarmrecords.length) {
                            resp.alarmrecords.sort(function(a, b) { return b.lastalarmtime - a.lastalarmtime; });
                            resp.alarmrecords.forEach(function(record) {
                                var isdispose = record.disposestatus === 0 ? self.$t("reportForm.untreated") : self.$t("reportForm.handled");
                                alarmRecords.push({
                                    devicename: vstore.state.deviceInfos[record.deviceid].devicename,
                                    alarmcount: record.alarmcount,
                                    lastalarmtimeStr: DateFormat.longToLocalDateTimeStr(record.lastalarmtime),
                                    startalarmtimeStr: DateFormat.longToLocalDateTimeStr(record.startalarmtime),
                                    isdispose: isdispose,
                                    stralarm: record.stralarm,
                                    stralarmen: record.stralarmen,
                                    disposeperson: record.disposeperson ? record.disposeperson : '',
                                    createrrecords: [],
                                });
                            });
                            self.alarmData = alarmRecords;
                        } else {
                            self.alarmData = [];
                        }
                    } else {
                        self.alarmData = [];
                    }
                    self.loading = false;
                });
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        computed: {
            calcHeight: function() {
                return this.lastTableHeight + 45;
            },
            needalarmCount: function() {
                var len = this.needalarmstr.length;
                var count = 0;
                for (var i = 0; i < len; i++) {
                    if (this.needalarmstr[i] == '1') {
                        count++;
                    }
                }
                return alarmTypeList.length == count ? (isZh ? '全选' : 'All') : count;
            }
        },
        mounted: function() {
            var me = this;
            me.groupslist = groupslist;
            me.queryDevicesTree();
            me.calcTableHeight();

            var needalarmstr = '';
            this.alarmTypeList.forEach(function(item, index) {
                me.checkboxObj[index] = true;
                item.show = true;
                needalarmstr += '1';
            })

            this.needalarmstr = needalarmstr;

            this.copyCheckboxObj = deepClone(me.checkboxObj);


            this.$nextTick(function() {
                if (isToAlarmListRecords) {
                    isToAlarmListRecords = false;
                    (function ball() {
                        if (me.zTreeObj) {
                            var node = utils.getTreeNodeByDeviceId(me.zTreeObj.getNodes(), globalDeviceId)
                            node.checked = true;
                            me.zTreeObj.selectNode(node);
                            me.sosoValue = globalDeviceId;
                            me.checkedDevice = [node];
                            me.selectedCount = 1;
                            me.onClickQuery();
                        } else {
                            setTimeout(ball, 100);
                        }
                    })();
                }
            });
        }
    })
}

//

function phoneAlarm(groupslist) {
    vueInstanse = new Vue({
        el: '#phone-alarm',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            tableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            isShowMatchDev: true,
            columns: [
                { type: 'index', width: 60, align: 'center' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 200 },
                { title: isZh ? '报警类型' : 'alarm Type', key: 'stralarm' },
                { title: isZh ? '时间' : 'date', key: 'datestr' },
                { title: isZh ? '结果' : 'result', key: 'notifyresult' },
            ],
            tableData: []
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devNum"),
                        isZh ? '报警类型' : 'alarm Type',
                        isZh ? '时间' : 'date',
                        isZh ? '结果' : 'result',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.stralarm);
                    itemArr.push(item.datestr);
                    itemArr.push(item.notifyresult);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.phoneAlarm') + '-' + this.queryDeviceId,
                    data: data,
                    dateRange: false,
                }
                new XlsxCls(options).exportExcel();
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return
                };
                var me = this;
                var url = myUrls.queryCallAlarm();
                var data = {
                    deviceid: this.queryDeviceId
                }
                this.loading = true;
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status === 0) {
                        var records = resp.records;
                        var tableData = [];
                        records.forEach(function(record) {
                            tableData.push({
                                deviceid: me.queryDeviceId,
                                notifyresult: record.notifyresult,
                                datestr: DateFormat.longToLocalDateTimeStr(new Date(record.lastalarmtime)),
                                stralarm: record.stralarm
                            })
                        });
                        me.tableData = tableData;
                    }
                    me.loading = false;
                })
            },
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.calcTableHeight();
            this.$nextTick(function() {
                if (isToPhoneAlarmRecords) {
                    isToPhoneAlarmRecords = false;
                    me.sosoValue = me.getDeviceTitle(globalDeviceId);
                    me.queryDeviceId = globalDeviceId;
                    me.onClickQuery();
                }
            });
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    });
}

function wechatAlarm(groupslist) {
    vueInstanse = new Vue({
        el: '#wechat-alarm',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            tableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            isShowMatchDev: true,
            columns: [
                { type: 'index', width: 60, align: 'center' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 200 },
                { title: isZh ? '报警类型' : 'alarm Type', key: 'stralarm' },
                { title: isZh ? '时间' : 'date', key: 'datestr' },
                { title: isZh ? '结果' : 'result', key: 'notifyresult' },
            ],
            tableData: []
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devNum"),
                        isZh ? '报警类型' : 'alarm Type',
                        isZh ? '时间' : 'date',
                        isZh ? '结果' : 'result',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.stralarm);
                    itemArr.push(item.datestr);
                    itemArr.push(item.notifyresult);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.wechatAlarm') + '-' + this.queryDeviceId,
                    data: data,
                    dateRange: false,
                }
                new XlsxCls(options).exportExcel();

            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return
                };
                var me = this;
                var url = myUrls.queryWechatAlarm();
                var data = {
                    deviceid: this.queryDeviceId
                }
                this.loading = true;
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status === 0) {
                        var records = resp.records;
                        var tableData = [];
                        records.forEach(function(record) {
                            tableData.push({
                                deviceid: me.queryDeviceId,
                                notifyresult: record.notifyresult,
                                datestr: DateFormat.longToLocalDateTimeStr(new Date(record.lastalarmtime)),
                                stralarm: record.stralarm
                            })
                        });
                        me.tableData = tableData;
                    }
                    me.loading = false;
                })
            },
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.calcTableHeight();
            this.$nextTick(function() {
                if (isToPhoneAlarmRecords) {
                    isToPhoneAlarmRecords = false;
                    me.sosoValue = me.getDeviceTitle(globalDeviceId);
                    me.queryDeviceId = globalDeviceId;
                    me.onClickQuery();
                }
            });
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    });
}


function rechargeRecords(groupslist) {
    vueInstanse = new Vue({
        el: '#recharge-records',
        i18n: utils.getI18n(),
        mixins: [reportMixin],
        data: {
            loading: false,
            tableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            isShowMatchDev: true,
            columns: [
                { type: 'index', width: 60, align: 'center' },
                { title: isZh ? '用户' : 'userName', key: 'username' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid' },
                { title: isZh ? '时间' : 'date', key: 'chargetimeStr' },
                { title: isZh ? '单号' : 'outtradeno', key: 'outtradeno' },
                { title: isZh ? '价格' : 'Price', key: 'fee' },
            ],
            tableData: []
        },
        methods: {
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        isZh ? '用户' : 'userName',
                        vRoot.$t("alarm.devNum"),
                        isZh ? '时间' : 'date',
                        isZh ? '单号' : 'outtradeno',
                        isZh ? '价格' : 'fee',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.username);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.chargetimeStr);
                    itemArr.push(item.outtradeno);
                    itemArr.push(item.username);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.rechargeRecords') + '-' + this.queryDeviceId,
                    data: data,
                }
                new XlsxCls(options).exportExcel();
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            onClickQuery: function() {

                var me = this;
                var url = myUrls.reportChargeCall();
                var data = {
                    username: userName,
                }

                this.queryDeviceId && (data.deviceid = this.queryDeviceId);

                utils.sendAjax(url, data, function(resp) {
                    if (resp.status === 0) {
                        var records = resp.records;
                        var tableData = [];
                        records.forEach(function(record) {
                            tableData.push({
                                username: record.username,
                                deviceid: record.deviceid,
                                chargetimeStr: DateFormat.longToLocalDateTimeStr(record.chargetime),
                                outtradeno: record.outtradeno,
                                fee: (record.fee / 100) + "元",
                            })
                        });
                        me.tableData = tableData;
                    }
                })
            },
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    });
}


function insureRecords(groupslist) {
    vueInstanse = new Vue({
        el: '#insure-records',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            exactValue: '',
            dayNumberType: 0,
            clearable: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            error: 123,
            createrToUser: userName,
            currentIndex: 1,
            total: 0,
            modal: false,
            columns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 70,
                    fixed: 'left',
                },
                {
                    title: vRoot.$t("reportForm.examine"),
                    key: 'isPay',
                    width: 100,
                    fixed: 'left',
                },
                { title: vRoot.$t("reportForm.name"), key: 'name', width: 100, fixed: 'left', },
                { title: vRoot.$t("reportForm.idNumber"), key: 'cardid', width: 160, fixed: 'left', },
                {
                    title: vRoot.$t("reportForm.policyNumber"),
                    width: 100,
                    fixed: 'left',
                    key: 'policyno',
                    "sortable": true,
                },
                { title: vRoot.$t("reportForm.addDate"), key: 'createtimeStr', width: 150, "sortable": true },
                {
                    title: vRoot.$t("reportForm.purchaseMethod"),
                    key: 'buytypeStr',
                    width: 100,
                },
                { title: vRoot.$t("reportForm.distributor"), key: 'username', width: 150 },
                { title: vRoot.$t("reportForm.distributorAddress"), key: 'useraddress', width: 150 },
                { title: vRoot.$t("reportForm.distributorPhone"), key: 'usernamephonenum', width: 120 },
                { title: vRoot.$t("reportForm.phonenum"), key: 'phonenum', width: 120 },
                { title: vRoot.$t("reportForm.usingaddress"), key: 'usingaddress', width: 150 },
                { title: vRoot.$t("reportForm.brandtype"), key: 'brandtype', width: 100 },
                { title: vRoot.$t("reportForm.vinno"), key: 'vinno', width: 150 },
                { title: vRoot.$t("reportForm.gpsid"), key: 'deviceid', width: 150 },
                { title: vRoot.$t("reportForm.buycarday"), key: 'buycarday', width: 100 },
                { title: vRoot.$t("reportForm.carvalue"), key: 'carvalue', width: 100 },
                { title: vRoot.$t("reportForm.insureprice"), key: 'insureprice', width: 100 },
                { title: vRoot.$t("reportForm.insurefee"), key: 'insurefee', width: 80 },
                {
                    title: vRoot.$t("reportForm.qualitycert"),
                    key: 'qualitycerturl',
                    width: 100,
                    render: function(h, parmas) {
                        if (parmas.row.qualitycerturl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.qualitycerturl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("reportForm.carpic"),
                    key: 'carpicurl',
                    width: 100,
                    render: function(h, parmas) {
                        if (parmas.row.carpicurl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.carpicurl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("reportForm.positivecardid"),
                    key: 'positivecardidurl',
                    width: 100,
                    render: function(h, parmas) {
                        if (parmas.row.positivecardidurl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.positivecardidurl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("reportForm.negativecardid"),
                    key: 'negativecardidurl',
                    width: 100,
                    render: function(h, parmas) {
                        if (parmas.row.negativecardidurl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.negativecardidurl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("reportForm.invoice"),
                    key: 'invoiceurl',
                    width: 100,
                    render: function(h, parmas) {
                        if (parmas.row.invoiceurl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.invoiceurl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("reportForm.groupphoto"),
                    key: 'groupphotourl',
                    width: 120,
                    render: function(h, parmas) {
                        if (parmas.row.groupphotourl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.groupphotourl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("reportForm.carkeypic"),
                    key: 'carkeypicurl',
                    width: 120,
                    render: function(h, parmas) {
                        if (parmas.row.carkeypicurl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.carkeypicurl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("reportForm.insurenotice"),
                    key: 'insurenoticeurl',
                    width: 120,
                    render: function(h, parmas) {
                        if (parmas.row.insurenoticeurl == null) {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                        return h('a', { attrs: { href: parmas.row.insurenoticeurl, target: '_blank' } }, vRoot.$t("reportForm.clickPreview"));
                    }
                },
                {
                    title: vRoot.$t("bgMgr.action"),
                    key: 'action',
                    width: 240,
                    fixed: 'right',
                    render: function(h, params) {
                        var isPay = params.row.insurestate == 1 ? true : false;
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.editDeviceIndex = params.index;
                                        vueInstanse.editObjectRow.name = params.row.name;
                                        vueInstanse.editObjectRow.cardid = params.row.cardid;
                                        vueInstanse.editObjectRow.phonenum = params.row.phonenum;
                                        vueInstanse.editObjectRow.vinno = params.row.vinno;
                                        vueInstanse.editObjectRow.usernamephonenum = params.row.usernamephonenum;
                                        vueInstanse.editObjectRow.insureid = params.row.insureid;
                                        vueInstanse.editObjectRow.isRecharge = isPay ? false : true;
                                        vueInstanse.handleEditInsure();
                                    }
                                }
                            }, isPay ? vRoot.$t("reportForm.cancelAudit") : vRoot.$t("reportForm.confirmAudit")),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.editDeviceIndex = params.index;
                                        vueInstanse.editObjectRow.name = params.row.name;
                                        vueInstanse.editObjectRow.cardid = params.row.cardid;
                                        vueInstanse.editObjectRow.phonenum = params.row.phonenum;
                                        vueInstanse.editObjectRow.vinno = params.row.vinno;
                                        vueInstanse.editObjectRow.usernamephonenum = params.row.usernamephonenum;
                                        vueInstanse.editObjectRow.insureid = params.row.insureid;
                                        vueInstanse.editObjectRow.isRecharge = params.row.insurestate == 1 ? true : false;
                                        vueInstanse.editObjectRow.createtime = new Date(params.row.createtimeStr);
                                        vueInstanse.modal = true;
                                    }
                                }
                            }, vRoot.$t("bgMgr.edit")),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small',
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.editDeviceIndex = params.index;
                                        vueInstanse.handleDelete(params.row);
                                    }
                                }
                            }, vRoot.$t("bgMgr.delete"))
                        ]);
                    }
                }
            ],
            tableHeight: 300,
            tableData: [],
            loading: false,
            isFilter: '2',
            editObjectRow: {
                name: '',
                cardid: '',
                phonenum: '',
                vinno: "",
                usernamephonenum: '',
                isRecharge: false,
                createtime: '',
            },
            disabled: true
        },
        methods: {
            cleanSelectedUser: function() {
                this.sosoValue = '';
            },
            searchValueChange: function() {
                if (this.groupslist !== null) {
                    this.searchfilterMethod(this.sosoValue.toLowerCase());
                } else {
                    console.log('tree数据还未返回');
                }
            },
            searchfilterMethod: function(value) {
                this.treeData = [];
                value = value.toLowerCase();
                this.treeData = this.variableDeepSearchIview(this.groupslist, value, 0);
                this.checkedDevice = [];
                if (this.isShowMatchDev == false) {
                    this.isShowMatchDev = true;
                }
            },
            variableDeepSearchIview: function(treeDataFilter, searchWord, limitcount) {
                var childTemp = [];
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var copyItem = null;
                    var item = treeDataFilter[i];
                    if (item != null) {
                        var isFound = false;
                        if (item.title.toLowerCase().indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                            copyItem = deepClone(item);
                            copyItem.expand = false;
                            isFound = true;
                        }
                        if (isFound == false && item.children && item.children.length > 0) {
                            var rs = that.variableDeepSearchIview(item.children, searchWord, limitcount);
                            if (rs && rs.length > 0) {
                                copyItem = deepClone(item);
                                copyItem.children = rs;
                                copyItem.expand = true;
                                isFound = true;
                            }
                        }
                        if (isFound == true) {
                            limitcount++;
                            childTemp.push(copyItem);
                            if (limitcount > 10) {
                                break;
                            }
                        }
                    }
                }
                return childTemp;
            },
            onChange: function(value) {
                this.dateVal = value;
            },
            handleEditInsure: function() {
                var url = myUrls.editInsure(),
                    me = this;
                this.editObjectRow.insurestate = me.editObjectRow.isRecharge ? 1 : 0;
                var d = deepClone(this.editObjectRow);
                if (d.createtime == "" || d.createtime == null) {
                    this.$Message.error(this.$t('message.plSelectTime'));
                    return;
                };
                d.createtime = new Date(d.createtime).getTime();

                utils.sendAjax(url, d, function(respData) {
                    if (respData.status == 0) {
                        var data = me.tableData[me.editDeviceIndex];
                        var cdata = me.insureRecords[data.index - 1];
                        data.name = me.editObjectRow.name;
                        data.cardid = me.editObjectRow.cardid;
                        data.phonenum = me.editObjectRow.phonenum;
                        data.vinno = me.editObjectRow.vinno;
                        data.usernamephonenum = me.editObjectRow.usernamephonenum;
                        data.insurestate = me.editObjectRow.isRecharge ? 1 : 0;
                        data.isPay = data.insurestate == 1 ? me.$t('reportForm.aeviewed') : me.$t('reportForm.notReviewed');
                        data.createtimeStr = DateFormat.longToDateStr(d.createtime, timeDifference);
                        data.createtime = data.createtime;

                        cdata.name = me.editObjectRow.name;
                        cdata.cardid = me.editObjectRow.cardid;
                        cdata.phonenum = me.editObjectRow.phonenum;
                        cdata.vinno = me.editObjectRow.vinno;
                        cdata.usernamephonenum = me.editObjectRow.usernamephonenum;
                        cdata.insurestate = me.editObjectRow.isRecharge ? 1 : 0;
                        cdata.isPay = data.insurestate == 1 ? me.$t('reportForm.aeviewed') : me.$t('reportForm.notReviewed');
                        cdata.createtimeStr = DateFormat.longToDateStr(d.createtime, timeDifference);
                        cdata.createtime = data.createtime;

                        me.modal = false;
                        me.$Message.success(me.$t('message.changeSucc'));
                    } else {
                        me.$Message.error(me.$t('message.changeFail'));
                    }
                })
            },
            handleDelete: function(row) {
                var index = this.editDeviceIndex,
                    me = this;
                this.$Modal.confirm({
                    title: me.$t('reportForm.tips'),
                    content: me.$t('reportForm.tipsContent'),
                    onOk: function() {
                        var url = myUrls.deleteInsure();
                        utils.sendAjax(url, { insureid: row.insureid }, function(respData) {
                            if (respData.status == 0) {
                                me.$Message.success(me.$t('message.deleteSucc'));
                                me.tableData.splice(index, 1);
                                me.insureRecords.splice(row.index - 1, 1);
                                me.total = me.insureRecords.length;
                            } else {
                                me.$Message.error(me.$t('message.deleteFail'));
                            }
                        });
                    },
                    onCancel: function() {}
                })

            },
            queryUsersTree: function(callback) {
                var url = myUrls.queryUsersTree(),
                    me = this;
                utils.sendAjax(url, { username: userName }, function(respData) {
                    if (respData.status == 0 && respData.rootuser.user) {
                        me.disabled = false;
                        callback([me.castUsersTreeToDevicesTree(respData.rootuser)]);
                    } else {
                        me.$Message.error(me.$t('monitor.queryFail'))
                    }
                });
            },
            castUsersTreeToDevicesTree: function(devicesTreeRecord) {
                var me = this;
                var iViewTree = {
                    render: function(h, params) {
                        var username = params.data.title;
                        return h('span', {
                            on: {
                                'click': function() {
                                    me.createrToUser = username;
                                    me.sosoValue = username;
                                }
                            },
                            style: {
                                cursor: 'pointer',
                                color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                            }
                        }, [
                            h('span', [
                                h('Radio', {
                                    props: {
                                        value: username == me.createrToUser
                                    },
                                    style: {
                                        marginRight: '4px',
                                        marginLeft: '4px'
                                    }
                                }),
                                h('span', params.data.title)
                            ]),
                        ])
                    },
                    expand: true,
                };
                if (devicesTreeRecord != null) {
                    var username = devicesTreeRecord.user.username;
                    var subusers = devicesTreeRecord.subusers;
                    iViewTree.title = username;
                    if (username != null && subusers != null && subusers.length > 0) {
                        var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                        iViewTree.children = subDevicesTreeRecord;

                    }
                }
                return iViewTree;
            },
            doCastUsersTreeToDevicesTree: function(usersTrees) {
                var devicesTreeRecord = [],
                    me = this;
                if (usersTrees != null && usersTrees.length > 0) {
                    for (var i = 0; i < usersTrees.length; ++i) {
                        var usersTree = usersTrees[i];
                        var username = usersTree.user.username;
                        var subusers = usersTree.subusers;
                        var currentsubDevicesTreeRecord = {
                            render: function(h, params) {
                                var username = params.data.title;
                                return h('span', {
                                    on: {
                                        'click': function() {
                                            me.createrToUser = username;
                                            me.sosoValue = username;
                                        }
                                    },
                                    style: {
                                        cursor: 'pointer',
                                        color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                                    }
                                }, [
                                    h('span', [
                                        h('Radio', {
                                            props: {
                                                value: username == me.createrToUser
                                            },
                                            style: {
                                                marginRight: '4px',
                                                marginLeft: '4px'
                                            }
                                        }),
                                        h('span', params.data.title)
                                    ]),
                                ])
                            },
                        };
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                            currentsubDevicesTreeRecord.children = subDevicesTreeRecord;
                        }
                        currentsubDevicesTreeRecord.title = username;
                        devicesTreeRecord.push(currentsubDevicesTreeRecord);
                    }
                }
                return devicesTreeRecord;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 165;
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentPageIndex = index;
                this.tableData = this.insureRecords.slice(start, offset);
            },
            changeTableColumns: function() {
                this.columns = this.getTableColumns();
            },
            queryInsures: function() {

                function buytypeStr(row) {
                    var buytype = row.buytype,
                        reslut = isZh ? '未知' : 'unknown';
                    if (buytype === 1) {
                        reslut = isZh ? '自行购买' : 'Self purchase';
                    } else if (buytype === 2) {
                        reslut = isZh ? '厂家购买' : 'manufactor';
                    }
                    return reslut;
                }


                this.loading = true;
                var url = myUrls.queryInsures(),
                    me = this,
                    startday = DateFormat.format(new Date(this.dateVal[0]), 'yyyy-MM-dd'),
                    endday = DateFormat.format(new Date(this.dateVal[1]), 'yyyy-MM-dd');
                utils.sendAjax(url, { username: this.createrToUser, startday: startday, endday: endday, offset: timeDifference }, function(resp) {
                    me.loading = false;
                    if (resp.status === 0 && resp.insures) {
                        //全部
                        if (me.isFilter == '0') {


                            me.insureRecords = (function() {
                                var tableData = [];
                                resp.insures.forEach(function(item, index) {
                                    item.index = index + 1;
                                    item.createtimeStr = DateFormat.longToDateStr(item.createtime, timeDifference)
                                    if (item.policyno == null) {
                                        item.policyno = vRoot.$t('reportForm.underReview');
                                    };
                                    if (item.insurestate !== 1) {
                                        item.index = tableData.length + 1;
                                        item.isPay = item.insurestate == 1 ? vRoot.$t('reportForm.aeviewed') : vRoot.$t('reportForm.notReviewed');
                                        tableData.push(item);
                                    };

                                    item.buytypeStr = buytypeStr(item);

                                })
                                return tableData;
                            })();
                        } else if (me.isFilter == '1') {
                            // me.insureRecords = resp.insures;
                            me.insureRecords = (function() {
                                var tableData = [];

                                resp.insures.forEach(function(item, index) {
                                    item.index = index + 1;
                                    item.createtimeStr = DateFormat.format(new Date(item.createtime), 'yyyy-MM-dd')
                                    if (item.policyno == null) {
                                        item.policyno = vRoot.$t('reportForm.underReview');
                                    };
                                    if (item.insurestate === 1) {
                                        item.index = tableData.length + 1;
                                        item.isPay = item.insurestate == 1 ? vRoot.$t('reportForm.aeviewed') : vRoot.$t('reportForm.notReviewed');
                                        tableData.push(item);
                                    };
                                })
                                return tableData;
                            })();
                        } else if (me.isFilter == '2') {
                            //2代表全部
                            resp.insures.forEach(function(item, index) {
                                item.index = index + 1;
                                if (item.policyno == null) {
                                    item.policyno = vRoot.$t('reportForm.underReview');
                                };
                                item.isPay = item.insurestate == 1 ? vRoot.$t('reportForm.aeviewed') : vRoot.$t('reportForm.notReviewed');
                                item.createtimeStr = DateFormat.format(new Date(item.createtime), 'yyyy-MM-dd')
                            })
                            me.insureRecords = resp.insures;
                        }
                        me.total = me.insureRecords.length;
                        me.currentIndex = 1;
                        me.tableData = me.insureRecords.slice(0, 20);
                    } else {
                        me.total = 0;
                        me.currentIndex = 1;
                        me.tableData = [];
                        me.insureRecords = [];
                    }

                }, function() {
                    me.loading = false;
                })
            },
            exactQueryInsures: function() {
                if (this.exactValue == '') {
                    this.$Message.error(vRoot.$t('reportForm.insurePlaceholder'));
                    return;
                };
                var url = myUrls.queryInsureByKeyWord(),
                    me = this;
                utils.sendAjax(url, { keyword: this.exactValue }, function(resp) {
                    me.loading = false;
                    if (resp.status == 0) {
                        resp.insures.forEach(function(item, index) {
                            item.index = index + 1;
                            if (item.policyno == null) {
                                item.policyno = vRoot.$t('reportForm.underReview');
                            };
                            item.isPay = item.insurestate == 1 ? vRoot.$t('reportForm.aeviewed') : vRoot.$t('reportForm.notReviewed');
                            item.createtimeStr = DateFormat.format(new Date(item.createtime), 'yyyy-MM-dd')
                        })
                        me.insureRecords = resp.insures;
                        me.total = me.insureRecords.length;
                        me.currentIndex = 1;
                        me.tableData = me.insureRecords.slice(0, 20);
                    } else {
                        me.$Message.error(vRoot.$t('monitor.queryFail'));
                    }
                }, function() {
                    me.loading = false;
                });
            },
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("reportForm.examine"),
                        vRoot.$t("reportForm.name"),
                        vRoot.$t("reportForm.idNumber"),
                        vRoot.$t("reportForm.policyNumber"),
                        vRoot.$t("reportForm.addDate"),
                        vRoot.$t("reportForm.purchaseMethod"),
                        vRoot.$t("reportForm.distributor"),
                        vRoot.$t("reportForm.distributorAddress"),
                        vRoot.$t("reportForm.distributorPhone"),
                        vRoot.$t("reportForm.phonenum"),
                        vRoot.$t("reportForm.usingaddress"),
                        vRoot.$t("reportForm.brandtype"),
                        vRoot.$t("reportForm.vinno"),
                        vRoot.$t("reportForm.gpsid"),
                        vRoot.$t("reportForm.buycarday"),
                        vRoot.$t("reportForm.carvalue"),
                        vRoot.$t("reportForm.insureprice"),
                        vRoot.$t("reportForm.insurefee"),
                    ]
                ];

                this.insureRecords.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.isPay);
                    itemArr.push(item.name);
                    itemArr.push(item.cardid);
                    itemArr.push(item.policyno);
                    itemArr.push(item.createtimeStr);
                    itemArr.push(item.buytypeStr);
                    itemArr.push(item.username);
                    itemArr.push(item.useraddress);
                    itemArr.push(item.usernamephonenum);
                    itemArr.push(item.phonenum);
                    itemArr.push(item.usingaddress);
                    itemArr.push(item.brandtype);
                    itemArr.push(item.vinno);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.buycarday);
                    itemArr.push(item.carvalue);
                    itemArr.push(item.insureprice);
                    itemArr.push(item.insurefee);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.insureData'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
        },
        mounted: function() {
            var me = this;
            me.queryUsersTree(function(usersTree) {
                me.groupslist = usersTree;
                me.treeData = usersTree;
            });
            this.sosoValue = userName;
            this.calcTableHeight();
            this.queryInsures();
            this.editDeviceIndex = null;
            this.insureRecords = [];
        },
    })
}

function salesRecord(groupslist) {
    vueInstanse = new Vue({
        el: '#sales-record',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isFilter: false,
            dayNumberType: 0,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            error: 123,
            createrToUser: userName,
            currentIndex: 1,
            total: 0,
            columns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 70,
                },
                {
                    title: vRoot.$t("reportForm.storeNumber"),
                    key: 'username',
                },
                {
                    title: vRoot.$t("reportForm.storeName"),
                    key: 'companyname'
                }, {
                    title: vRoot.$t("reportForm.name"),
                    key: 'cardname'
                }, {
                    title: vRoot.$t("customer.contactNumber"),
                    key: 'phone'
                }, {
                    title: vRoot.$t("reportForm.address"),
                    key: 'companyaddr'
                }, {
                    title: vRoot.$t("reportForm.cumulativeRecords"),
                    key: 'totalinsurecount'
                },
                {
                    title: vRoot.$t("reportForm.surplus"),
                    key: 'remaininsurecount',
                },
                {
                    title: vRoot.$t("reportForm.exFactory"),
                    key: 'agentinsurecount',
                },
                {
                    title: vRoot.$t("reportForm.buyOneself"),
                    key: 'individualinsurecount',
                },
            ],
            tableHeight: 300,
            tableData: [],
            loading: false,
            disabled: true
        },
        methods: {
            cleanSelectedUser: function() {
                this.sosoValue = '';
            },
            searchValueChange: function() {
                if (this.groupslist !== null) {
                    this.searchfilterMethod(this.sosoValue.toLowerCase());
                } else {
                    console.log('tree数据还未返回');
                }
            },
            searchfilterMethod: function(value) {
                this.treeData = [];
                value = value.toLowerCase();
                this.treeData = this.variableDeepSearchIview(this.groupslist, value, 0);
                this.checkedDevice = [];
                if (this.isShowMatchDev == false) {
                    this.isShowMatchDev = true;
                }
            },
            variableDeepSearchIview: function(treeDataFilter, searchWord, limitcount) {
                var childTemp = [];
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var copyItem = null;
                    var item = treeDataFilter[i];
                    if (item != null) {
                        var isFound = false;
                        if (item.title.toLowerCase().indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                            copyItem = deepClone(item);
                            copyItem.expand = false;
                            isFound = true;
                        }
                        if (isFound == false && item.children && item.children.length > 0) {
                            var rs = that.variableDeepSearchIview(item.children, searchWord, limitcount);
                            if (rs && rs.length > 0) {
                                copyItem = deepClone(item);
                                copyItem.children = rs;
                                copyItem.expand = true;
                                isFound = true;
                            }
                        }
                        if (isFound == true) {
                            limitcount++;
                            childTemp.push(copyItem);
                            if (limitcount > 10) {
                                break;
                            }
                        }
                    }
                }
                return childTemp;
            },
            handleSelectdDate: function(dayNumber) {
                this.dayNumberType = dayNumber;
                var dayTime = 24 * 60 * 60 * 1000;
                if (dayNumber == 0) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
                } else if (dayNumber == 1) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime, timeDifference), DateFormat.longToDateStr(Date.now() - dayTime, timeDifference)];
                } else if (dayNumber == 3) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 2, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
                } else if (dayNumber == 7) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 6, timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)];
                }
            },
            onChange: function(value) {
                this.dateVal = value;
            },
            queryUsersTree: function(callback) {
                var url = myUrls.queryUsersTree(),
                    me = this;
                utils.sendAjax(url, { username: userName }, function(respData) {
                    if (respData.status == 0 && respData.rootuser.user) {
                        me.disabled = false;
                        callback([me.castUsersTreeToDevicesTree(respData.rootuser)]);
                    } else {
                        me.$Message.error(me.$t('monitor.queryFail'));
                    }
                });
            },
            castUsersTreeToDevicesTree: function(devicesTreeRecord) {
                var me = this;
                var iViewTree = {
                    render: function(h, params) {
                        var username = params.data.title;
                        return h('span', {
                            on: {
                                'click': function() {
                                    me.createrToUser = username;
                                    me.sosoValue = username;
                                }
                            },
                            style: {
                                cursor: 'pointer',
                                color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                            }
                        }, [
                            h('span', [
                                h('Radio', {
                                    props: {
                                        value: username == me.createrToUser
                                    },
                                    style: {
                                        marginRight: '4px',
                                        marginLeft: '4px'
                                    }
                                }),
                                h('span', params.data.title)
                            ]),
                        ])
                    },
                    expand: true,
                };
                if (devicesTreeRecord != null) {
                    var username = devicesTreeRecord.user.username;
                    var subusers = devicesTreeRecord.subusers;
                    iViewTree.title = username;
                    if (username != null && subusers != null && subusers.length > 0) {
                        var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                        iViewTree.children = subDevicesTreeRecord;
                    }
                }
                return iViewTree;
            },
            doCastUsersTreeToDevicesTree: function(usersTrees) {
                var devicesTreeRecord = [],
                    me = this;
                if (usersTrees != null && usersTrees.length > 0) {
                    for (var i = 0; i < usersTrees.length; ++i) {
                        var usersTree = usersTrees[i];
                        var username = usersTree.user.username;
                        var subusers = usersTree.subusers;
                        var currentsubDevicesTreeRecord = {
                            render: function(h, params) {
                                var username = params.data.title;
                                return h('span', {
                                    on: {
                                        'click': function() {
                                            me.createrToUser = username;
                                            me.sosoValue = username;
                                        }
                                    },
                                    style: {
                                        cursor: 'pointer',
                                        color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                                    }
                                }, [
                                    h('span', [
                                        h('Radio', {
                                            props: {
                                                value: username == me.createrToUser
                                            },
                                            style: {
                                                marginRight: '4px',
                                                marginLeft: '4px'
                                            }
                                        }),
                                        h('span', params.data.title)
                                    ]),
                                ])
                            },
                        };
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                            currentsubDevicesTreeRecord.children = subDevicesTreeRecord;
                        }

                        currentsubDevicesTreeRecord.title = username;
                        devicesTreeRecord.push(currentsubDevicesTreeRecord);
                    }
                }
                return devicesTreeRecord;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 165;
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentPageIndex = index;
                this.tableData = this.insureRecords.slice(start, offset);
            },
            changeTableColumns: function() {
                this.columns = this.getTableColumns();
            },
            queryInsures: function() {
                this.loading = true;
                var url = myUrls.reportInsure(),
                    me = this,
                    startday = DateFormat.format(new Date(this.dateVal[0]), 'yyyy-MM-dd'),
                    endday = DateFormat.format(new Date(this.dateVal[1]), 'yyyy-MM-dd');
                utils.sendAjax(url, { username: this.createrToUser, startday: startday, endday: endday, offset: timeDifference }, function(resp) {
                    me.loading = false;
                    if (resp.status === 0) {
                        if (me.isFilter) {
                            var filters = [];
                            var index = 1;
                            resp.records.forEach(function(item) {
                                if (item.agentinsurecount != 0 || item.individualinsurecount != 0 || item.remaininsurecount != 0) {
                                    filters.push(item);
                                    index++;
                                }
                            });
                            me.insureRecords = filters;
                        } else {
                            resp.records.forEach(function(item, index) {
                                item.index = index + 1;
                            });
                            me.insureRecords = resp.records;
                        }


                        me.total = me.insureRecords.length;
                        me.currentIndex = 1;
                        me.tableData = me.insureRecords.slice(0, 20);
                    } else {
                        me.total = 0;
                        me.currentIndex = 1;
                        me.tableData = [];
                        me.insureRecords = [];
                    }

                }, function() {
                    me.loading = false;
                })
            },
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("reportForm.storeNumber"),
                        vRoot.$t("reportForm.storeName"),
                        vRoot.$t("reportForm.name"),
                        vRoot.$t("customer.contactNumber"),
                        vRoot.$t("reportForm.address"),
                        vRoot.$t("reportForm.cumulativeRecords"),
                        vRoot.$t("reportForm.surplus"),
                        vRoot.$t("reportForm.exFactory"),
                        vRoot.$t("reportForm.buyOneself"),
                    ]
                ];

                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.username);
                    itemArr.push(item.companyname);
                    itemArr.push(item.cardname);
                    itemArr.push(item.phone);
                    itemArr.push(item.companyaddr);
                    itemArr.push(item.totalinsurecount);
                    itemArr.push(item.remaininsurecount);
                    itemArr.push(item.agentinsurecount);
                    itemArr.push(item.individualinsurecount);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.insureData'),
                    data: data,
                    dateRange: false,
                }
                new XlsxCls(options).exportExcel();

            },
        },
        mounted: function() {
            var me = this;
            me.queryUsersTree(function(usersTree) {
                me.groupslist = usersTree;
                me.treeData = usersTree;
            });
            this.sosoValue = userName;
            this.calcTableHeight();
            // this.queryInsures();
            this.editDeviceIndex = null;
            this.insureRecords = [];
        },
    })
}




//综合上线统计
function reportOnlineSummary(groupslist) {
    vueInstanse = new Vue({
        i18n: utils.getI18n(),
        el: "#reportonlinesummary",
        mixins: [treeMixin],
        data: {
            multiple: false,
            createrToUser: userName,
            userlists: globalUserList,
            groupslist: [],
            iconState: 'ios-arrow-down',
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 60 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', sortable: true, },
                { title: vRoot.$t('alarm.devNum'), key: 'deviceid', },
                { title: 'SIM', key: 'simnum', sortable: true },
                {
                    title: vRoot.$t('monitor.groupName'),
                    key: 'groupName',
                },
                {
                    title: vRoot.$t('user.devType'),
                    key: 'typename',
                    sortable: true,
                    width: 140,
                },
                {
                    title: vRoot.$t('reportForm.operationStatus'),
                    width: 85,
                    key: 'operationStatus',
                },
                {
                    title: vRoot.$t('reportForm.updateTime'),
                    width: 150,
                    key: 'updatetimeStr',
                },
                {
                    title: vRoot.$t('reportForm.lastAddress'),
                    key: 'lastAddress',

                },
                { title: vRoot.$t('reportForm.lastState'), key: 'strstatus', },
                {
                    title: vRoot.$t('customer.remark'),
                    key: 'remark',
                    render: function(h, params) {
                        var remark = params.row.remark;
                        return h('div', {
                            style: {
                                maxHeight: '40px',
                                overflow: 'hidden'
                            }
                        }, remark)
                    }
                },
            ],
            tableData: [],
            tableHeight: 300,
            loading: false,
            totalVehicle: 0,
            onlineVehicle: 0,
            offlineVehicle: 0,
            posiVehicle: 0, // 定位数量
            notPosiVehicle: 0, // 不定位数量
        },
        methods: {
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t('alarm.devNum'),
                        'SIM',
                        vRoot.$t('monitor.groupName'),
                        vRoot.$t('user.devType'),
                        vRoot.$t('reportForm.operationStatus'),
                        vRoot.$t('reportForm.updateTime'),
                        vRoot.$t('reportForm.lastAddress'),
                        vRoot.$t('reportForm.lastState'),
                        vRoot.$t('customer.remark'),
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.simnum ? item.simnum : '');
                    itemArr.push(item.groupName);
                    itemArr.push(item.typename);
                    itemArr.push(item.operationStatus);
                    itemArr.push(item.updatetimeStr);
                    itemArr.push(item.lastAddress);
                    itemArr.push(item.strstatus ? item.strstatus : '');
                    itemArr.push(item.remark ? item.remark : '');
                    data.push(itemArr);
                });

                var dateRange = this.$t("reportForm.vehicleTotal") + ':' + this.totalVehicle + ',' +
                    this.$t("reportForm.onlineTotal") + ':' + this.onlineVehicle + ',' +
                    this.$t("reportForm.offlineTotal") + ':' + this.offlineVehicle + ',' +
                    this.$t("reportForm.locationTotal") + ':' + this.posiVehicle + ',' +
                    this.$t("reportForm.notLocationTotal") + ':' + this.notPosiVehicle;
                var options = {
                    title: vRoot.$t('reportForm.comprehensiveStatistics'),
                    data: data,
                    dateRange: dateRange
                }
                new XlsxCls(options).exportExcel();

            },
            onClickQuery: function() {
                if (globalUserList.indexOf(this.createrToUser) == -1) {
                    this.$Message.error(this.$t("message.selectCorrectAccount"));
                    return;
                }
                this.totalVehicle = 0;
                this.onlineVehicle = 0;
                this.offlineVehicle = 0;
                this.posiVehicle = 0; // 定位数量
                this.notPosiVehicle = 0; // 不定位数量
                this.loading = true;
                var url = myUrls.reportOnlineSummary(),
                    me = this;
                utils.sendAjax(url, { username: this.createrToUser }, function(respData) {
                    me.loading = false;
                    if (respData.status === 0) {
                        if (respData.records == null) return;
                        me.tableData = respData.records;
                        me.totalVehicle = me.tableData.length;
                        me.tableData.forEach(function(item, index) {
                            item.index = index + 1;
                            var updatetime = item.updatetime;
                            var callat = item.callat;
                            var callon = item.callon;
                            var updatetimeStr = isZh ? '未上报' : 'null';
                            var devicetype = item.devicetype;
                            var type = vstore.state.deviceTypes[devicetype];
                            var typename = type ? type.typename : '';
                            item.typename = typename;
                            if (updatetime > 0) {
                                updatetimeStr = DateFormat.longToLocalDateTimeStr(updatetime);
                            }
                            item.updatetimeStr = updatetimeStr;

                            if (updatetime > 0 && (Date.now() - updatetime) < 60 * 10 * 1000) {
                                me.onlineVehicle++;
                                item.operationStatus = vRoot.$t('monitor.online');
                            } else {
                                me.offlineVehicle++;
                                item.operationStatus = vRoot.$t('monitor.offline');
                            }
                            item.groupName = utils.getGroupName(groupslist, item.deviceid);
                            if (callat == 0 && callon == 0) {
                                me.notPosiVehicle++;
                                item.lastAddress = vRoot.$t('reportForm.notLocated')
                            } else {
                                me.posiVehicle++;
                                item.lastAddress = vRoot.$t('reportForm.located')
                            }
                        });
                    } else {
                        me.$Message.error('查询失败');
                    }
                });

            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 167;
            },
            queryUsersTree: function(callback) {
                var url = myUrls.queryUsersTree(),
                    me = this;
                utils.sendAjax(url, { username: userName }, function(respData) {
                    if (respData.status == 0 && respData.rootuser.user) {
                        me.disabled = false;
                        callback([me.castUsersTreeToDevicesTree(respData.rootuser)]);
                    } else {
                        me.$Message.error(me.$t('monitor.queryFail'))
                    }
                });
            },
            castUsersTreeToDevicesTree: function(devicesTreeRecord) {
                var me = this;
                var iViewTree = {
                    render: function(h, params) {
                        var username = params.data.title;
                        return h('span', {
                            on: {
                                'click': function() {
                                    me.createrToUser = username;
                                    me.sosoValue = username;
                                }
                            },
                            style: {
                                cursor: 'pointer',
                                color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                            }
                        }, [
                            h('span', [
                                h('Radio', {
                                    props: {
                                        value: username == me.createrToUser
                                    },
                                    style: {
                                        marginRight: '4px',
                                        marginLeft: '4px'
                                    }
                                }),
                                h('span', params.data.title)
                            ]),
                        ])
                    },
                    expand: true,
                };
                if (devicesTreeRecord != null) {
                    var username = devicesTreeRecord.user.username;
                    var subusers = devicesTreeRecord.subusers;
                    iViewTree.title = username;
                    if (username != null && subusers != null && subusers.length > 0) {
                        var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                        iViewTree.children = subDevicesTreeRecord;

                    }
                }
                return iViewTree;
            },
            doCastUsersTreeToDevicesTree: function(usersTrees) {
                var devicesTreeRecord = [],
                    me = this;
                if (usersTrees != null && usersTrees.length > 0) {
                    for (var i = 0; i < usersTrees.length; ++i) {
                        var usersTree = usersTrees[i];
                        var username = usersTree.user.username;
                        var subusers = usersTree.subusers;
                        var currentsubDevicesTreeRecord = {
                            render: function(h, params) {
                                var username = params.data.title;
                                return h('span', {
                                    on: {
                                        'click': function() {
                                            me.createrToUser = username;
                                            me.sosoValue = username;
                                        }
                                    },
                                    style: {
                                        cursor: 'pointer',
                                        color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                                    }
                                }, [
                                    h('span', [
                                        h('Radio', {
                                            props: {
                                                value: username == me.createrToUser
                                            },
                                            style: {
                                                marginRight: '4px',
                                                marginLeft: '4px'
                                            }
                                        }),
                                        h('span', params.data.title)
                                    ]),
                                ])
                            },
                        };
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                            currentsubDevicesTreeRecord.children = subDevicesTreeRecord;
                        }
                        currentsubDevicesTreeRecord.title = username;
                        devicesTreeRecord.push(currentsubDevicesTreeRecord);
                    }
                }
                return devicesTreeRecord;
            },
            cleanSearchVal: function() {
                this.sosoValue = '';
            },
            searchValueChange: function() {
                if (this.groupslist !== null) {
                    this.searchfilterMethod(this.sosoValue.toLowerCase());
                } else {
                    console.log('tree数据还未返回');
                }
            },
            searchfilterMethod: function(value) {
                this.treeData = [];
                value = value.toLowerCase();
                this.treeData = this.variableDeepSearchIview(this.groupslist, value, 0);
                this.checkedDevice = [];
                if (this.isShowMatchDev == false) {
                    this.isShowMatchDev = true;
                }
            },
            variableDeepSearchIview: function(treeDataFilter, searchWord, limitcount) {
                var childTemp = [];
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var copyItem = null;
                    var item = treeDataFilter[i];
                    if (item != null) {
                        var isFound = false;
                        if (item.title.toLowerCase().indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                            copyItem = deepClone(item);
                            copyItem.expand = false;
                            isFound = true;
                        }
                        if (isFound == false && item.children && item.children.length > 0) {
                            var rs = that.variableDeepSearchIview(item.children, searchWord, limitcount);
                            if (rs && rs.length > 0) {
                                copyItem = deepClone(item);
                                copyItem.children = rs;
                                copyItem.expand = true;
                                isFound = true;
                            }
                        }
                        if (isFound == true) {
                            limitcount++;
                            childTemp.push(copyItem);
                            if (limitcount > 10) {
                                break;
                            }
                        }
                    }
                }
                return childTemp;
            },
        },
        watch: {
            sosoValue: function(newVal) {
                this.createrToUser = newVal;
            }
        },
        mounted: function() {
            var me = this;
            this.calcTableHeight();
            this.sosoValue = userName;
            this.queryUsersTree(function(usersTree) {
                me.groupslist = usersTree;
                me.treeData = usersTree;
            });
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}

// 掉线报表
function dropLineReport(groupslist) {
    vueInstanse = new Vue({
        i18n: utils.getI18n(),
        el: "#droplinereport",
        mixins: [treeMixin],
        data: {
            isSpin: false,
            loading: false,
            days: '1',
            groupslist: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), key: 'index', width: 65 },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 120, sortable: true },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 120, sortable: true },
                { title: vRoot.$t('reportForm.offlineTime'), width: 150, key: 'updatetimeStr', sortable: true },
                { title: vRoot.$t('reportForm.downOfflineDuration'), width: 180, key: 'downOfflineDuration', sortable: true },
                { title: vRoot.$t("reportForm.drivername"), key: 'drivername', width: 120 },
                { title: vRoot.$t("customer.contactNumber"), key: 'driverphone', width: 120 },
                { title: 'SIM', key: 'simnum', width: 120 },
                { title: vRoot.$t("monitor.groupName"), key: 'groupName', width: 100 },
                { title: vRoot.$t("user.devType"), key: 'devicetype', width: 85 },
                { title: vRoot.$t("monitor.ownerInfo"), key: 'ownername', width: 100 },
                { title: vRoot.$t("device.contact1"), key: 'phonenum1', width: 120 },
                { title: vRoot.$t("device.contact2"), key: 'phonenum2', width: 120 },
                { title: vRoot.$t('reportForm.stralarm'), width: 200, key: 'stralarm' },
                { title: vRoot.$t('reportForm.strstatus'), width: 200, key: 'strstatus' },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 120,
                    render: function(h, params) {
                        return h('Button', {
                            props: {
                                size: "small",
                            },
                            on: {
                                click: function() {
                                    utils.showWindowMap(vueInstanse, params);
                                }
                            },
                        }, isZh ? '查看地图' : 'See Map')
                    }
                },
            ],
            mapModal: false,
            tableData: [],
            tableHeight: 300,
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t('reportForm.offlineTime'),
                        vRoot.$t('reportForm.downOfflineDuration') + '(H)',
                        vRoot.$t("reportForm.drivername"),
                        vRoot.$t("customer.contactNumber"),
                        'SIM',
                        vRoot.$t("monitor.groupName"),
                        vRoot.$t("user.devType"),
                        vRoot.$t("monitor.ownerInfo"),
                        vRoot.$t("device.contact1"),
                        vRoot.$t("device.contact2"),
                        vRoot.$t('reportForm.stralarm'),
                        vRoot.$t('reportForm.strstatus'),
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.updatetimeStr);
                    itemArr.push(item.downOfflineDuration);
                    itemArr.push(item.drivername ? item.drivername : '');
                    itemArr.push(item.driverphone ? item.driverphone : '');
                    itemArr.push(item.simnum ? item.simnum : '');
                    itemArr.push(item.groupName);
                    itemArr.push(item.devicetype);
                    itemArr.push(item.ownername ? item.ownername : '');
                    itemArr.push(item.phonenum1 ? item.phonenum1 : '');
                    itemArr.push(item.phonenum2 ? item.phonenum2 : '');
                    itemArr.push(item.stralarm);
                    itemArr.push(item.strstatus);
                    data.push(itemArr);
                });
                var options = {
                    title: isZh ? "离线报表" : "OfflineReport",
                    data: data,
                }
                new XlsxCls(options).exportExcel();


            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('posi-map');
            },
            onClickQuery: function() {
                if (this.checkedDevice.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.loading = true;
                var url = myUrls.reportOffline(),
                    me = this;
                var data = {
                    deviceids: [],
                    offlinehours: Number(this.days)
                }
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid) {
                            data.deviceids.push(group.deviceid);
                        }

                    }
                });

                function getUpdatetimeStr(row) {
                    var updatetime = row.updatetime;
                    var updatetimeStr = isZh ? '未上报' : 'null';
                    if (updatetime > 0) {
                        updatetimeStr = DateFormat.longToLocalDateTimeStr(updatetime);
                    }
                    return updatetimeStr;
                }

                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    if (respData.status == 0) {

                        respData.records.forEach(function(item, index) {
                            var typeInfo = vstore.state.deviceTypes[item.devicetype];
                            item.index = index + 1;
                            item.updatetimeStr = getUpdatetimeStr(item);
                            item.devicetype = typeInfo ? typeInfo.typename : '';
                            item.downOfflineDuration = ((Date.now() - item.updatetime) / 1000 / 3600).toFixed(2);
                            item.groupName = me.getGroupName(groupslist, item);

                            var deviceex = item.deviceex;
                            if (deviceex) {
                                item.ownername = deviceex.ownername;
                                item.phonenum1 = deviceex.phonenum1;
                                item.phonenum2 = deviceex.phonenum2;
                                item.drivername = deviceex.drivername;
                                item.driverphone = deviceex.driverphone;
                            } else {
                                item.ownername = '';
                                item.phonenum1 = '';
                                item.phonenum2 = '';
                                item.drivername = '';
                                item.driverphone = '';
                            }

                            if (!isZh) {
                                item.stralarm = item.stralarmen;
                                item.strstatus = item.strstatusen;
                            }
                        });

                        me.tableData = respData.records;
                    } else {
                        me.$Message.error(me.$t('monitor.queryFail'));
                    }
                });
            },
            getGroupName: function(groupslist, row) {
                var groupid = row.groupid;
                var deviceid = row.deviceid;
                var groupName = '';
                if (groupid == 0) {
                    groupName = vRoot.$t("monitor.defaultGroup");
                } else {
                    for (var i = 0; i < groupslist.length; i++) {
                        var group = groupslist[i];
                        for (var j = 0; j < group.devices.length; j++) {
                            var device = group.devices[j];

                            if (device.deviceid === deviceid) {
                                if (group.groupname.indexOf('-') == -1) {
                                    groupName = group.groupname;
                                } else {
                                    groupName = group.groupname.split('-')[1];
                                }
                                break;
                            }
                            if (groupName != '') { break };
                        }
                    }
                }
                return groupName;
            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            this.queryDevicesTree();
            this.initMap();
            window.onresize = function() {
                me.calcTableHeight();
            };
        },
        created: function() {
            this.checkedDevice = [];
        },
    })
}

// 每日在线率
function deviceOnlineDaily(groupslist) {

    vueInstanse = new Vue({
        el: "#deviceonlinedaily",
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            groupslist: [],
            tableHeight: 300,
            loading: false,
            yearMonth: new Date(),
            daycount: 0,
            columns: [
                { type: 'index', width: 120 },
                { title: vRoot.$t("reportForm.ascriptionUser"), key: 'username' },
                { title: vRoot.$t('alarm.devNum'), key: 'deviceid' },
                { title: vRoot.$t('alarm.devName'), key: 'devicename' },
            ],
            tableData: [],
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.ascriptionUser"),
                    ]
                ];


                for (var i = 1; i <= this.daycount; i++) {
                    var key = String(i);
                    data[0].push(key);
                }

                data[0].push(vRoot.$t("reportForm.onlineRate"));

                var me = this;

                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.username);
                    for (var i = 1; i <= me.daycount; i++) {
                        var key = String(i);
                        itemArr.push(item[key]);
                    }
                    itemArr.push(item.onlineRate);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.dailyVehicleOnlineRate') + '-' + this.queryDateRange,
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },

            onClickQuery: function() {
                if (this.checkedDevice.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.loading = true;
                var url = myUrls.reportDeviceOnlineDaily(),
                    me = this;
                var data = {
                    deviceids: [],
                    offset: timeDifference,
                    year: this.yearMonth.getFullYear(),
                    month: this.yearMonth.getMonth() + 1,
                }
                this.checkedDevice.forEach(function(group) {
                    me.queryDateRange = me.yearMonth.getFullYear() + '-' + (me.yearMonth.getMonth() + 1)
                    if (!group.children) {
                        if (group.deviceid != null) {
                            data.deviceids.push(group.deviceid);
                        } else {
                            isNull = true;
                        }
                    }
                });
                if (data.deviceids.length === 0) {
                    this.$Message.error("选择组没有设备!");
                    return;
                }
                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    if (respData.status === 0) {
                        me.daycount = respData.daycount;
                        me.tableData = me.getTableData(respData.records);
                    }
                })
            },
            getTableData: function(records) {
                var tableData = [];
                records.forEach(function(item) {
                    var tableItem = {
                        username: userName
                    };
                    var onlineCount = 0;
                    tableItem.deviceid = item.deviceid;
                    item.daysstatus.forEach(function(item, idx) {
                        var isOnline = item == 0 ? false : true;
                        if (isOnline) {
                            onlineCount++;
                            tableItem[String(++idx)] = '1';
                        } else {
                            tableItem[String(++idx)] = '0';
                        }
                    })
                    var onlineRate = (onlineCount / item.daysstatus.length) * 100;
                    tableItem['onlineRate'] = onlineRate.toFixed(2) + '%';
                    tableData.push(tableItem);
                });
                return tableData;
            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        watch: {
            daycount: function(newVla) {
                var columns = [
                    { type: 'index', width: 60, fixed: 'left' },
                    {
                        title: vRoot.$t("reportForm.ascriptionUser"),
                        key: 'username',
                        fixed: 'left',
                        width: 120,
                        render: function(h, parmas) {
                            var deviceid = parmas.row.deviceid;
                            var userName = "";
                            vueInstanse.checkedDevice.forEach(function(group) {
                                if (!group.children) {
                                    if (group.deviceid === deviceid) {
                                        userName = group.username;
                                    }
                                }
                            });
                            return h('span', {}, userName);
                        }
                    },
                    {
                        title: vRoot.$t("alarm.devName"),
                        key: 'devicename',
                        fixed: 'left',
                        width: 140,
                        render: function(h, params) {
                            var deviceid = params.row.deviceid;
                            for (var i = 0; i < groupslist.length; i++) {
                                var group = groupslist[i];
                                for (var j = 0; j < group.devices.length; j++) {
                                    var device = group.devices[j];
                                    if (device.deviceid == deviceid) {
                                        return h('span', {}, device.devicename);
                                    }
                                }
                            };
                            return h('span', {}, '');
                        }
                    },
                    { title: vRoot.$t("alarm.devNum"), key: 'deviceid', fixed: 'left', width: 140 },
                ]
                for (var i = 1; i <= newVla; i++) {
                    var key = String(i);
                    columns.push({
                        title: key,
                        key: key,
                        width: 60,
                    })
                }
                columns.push({
                    key: 'onlineRate',
                    title: vRoot.$t("reportForm.onlineRate"),
                    fixed: 'right',
                    sortable: true,
                    width: 120,
                });
                this.columns = columns;
            },
        },
        mounted: function() {
            var me = this;
            this.queryDevicesTree();
            window.onresize = function() {
                me.calcTableHeight();
            };
        },
        created: function() {
            this.checkedDevice = [];
        },
    })
}

// 车队日在线率
function groupsOnlineDaily(groupslist) {
    vueInstanse = new Vue({
        el: '#groupsonlinedaily',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            groupslist: [],
            tableHeight: 300,
            loading: false,
            yearMonth: new Date(),
            columns: [
                { type: 'index', width: 60 },
                { title: vRoot.$t("reportForm.ascriptionUser"), key: 'username' },
                { title: vRoot.$t("monitor.groupName"), key: 'groupname' },
                {
                    title: vRoot.$t("reportForm.onlinequantityAndTotalquantity"),
                    key: 'onlinecountAndTotalcount',
                },
                {
                    title: vRoot.$t("reportForm.dailyOnlineRate"),
                    sortable: true,
                    key: 'dailyOnlineRate',
                },
            ],
            tableData: [],
        },
        methods: {
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("reportForm.ascriptionUser"),
                        vRoot.$t("monitor.groupName"),
                        vRoot.$t("reportForm.onlinequantityAndTotalquantity"),
                        vRoot.$t("reportForm.dailyOnlineRate"),
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.username);
                    itemArr.push(item.groupname ? item.groupname : '');
                    itemArr.push(item.onlinecountAndTotalcount);
                    itemArr.push(item.dailyOnlineRate);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.dailyFleetOnlineRate'),
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();
            },
            onClickQuery: function() {
                if (this.checkedDevice.length == 0) {
                    this.$Message.error("请选择分组");
                    return;
                }
                this.loading = true;
                var url = myUrls.reportGroupOnlineDaily(),
                    me = this;
                var data = {
                    groups: [],
                    offset: timeDifference,
                    daystr: DateFormat.format(this.yearMonth, 'yyyy-MM-dd'),
                }

                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        data.groups.push({
                            username: group.username,
                            groupid: group.groupid,
                            groupname: group.groupname,
                        })
                    }
                });

                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    me.queryDateRange = data.daystr
                    if (respData.status == 0) {
                        if (respData.records != null) {
                            respData.records.forEach(function(item) {

                                var onlinecount = item.onlinecount;
                                var totalcount = item.totalcount;
                                item.onlinecountAndTotalcount = onlinecount + "/" + totalcount;

                                var onlineRate = (onlinecount / totalcount) * 100;
                                if (totalcount == 0) {
                                    item.dailyOnlineRate = "0.00%";
                                } else {
                                    item.dailyOnlineRate = onlineRate.toFixed(2) + "%";
                                }
                            });
                            me.tableData = respData.records;
                        }
                    }
                });
            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            this.queryDevicesTree();
            window.onresize = function() {
                me.calcTableHeight();
            };
        },
        created: function() {
            this.checkedDevice = [];
        },
    })
}

// 车辆月在线
function deviceMonthOnlineDaily(groupslist) {
    vueInstanse = new Vue({
        el: "#devicemonthonlinedaily",
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            modal: false,
            textTop: isZh ? ["日", "一", "二", "三", "四", "五", "六"] : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            datesArr: [],
            year: 1970,
            month: 1,
            groupslist: [],
            tableHeight: 300,
            loading: false,
            yearMonth: new Date(),
            daycount: 0,
            columns: [
                { type: 'index', width: 60 },
                {
                    title: vRoot.$t("reportForm.ascriptionUser"),
                    key: 'username',
                    width: 130,
                },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid' },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                },
                {
                    title: vRoot.$t("reportForm.onlineDaysAndTotalDays"),
                    key: 'onlineDaysAndTotalDays',
                },
                { title: vRoot.$t("reportForm.onlineRate"), key: 'onlineRate', sortable: true },
                {
                    title: vRoot.$t("reportForm.onlineDate"),
                    render: function(h, params) {
                        var onlineDate = vRoot.$t("reportForm.onlineDate");
                        var row = params.row;
                        return h(
                            'Button', {
                                on: {
                                    click: function() {
                                        vueInstanse.year = row.year;
                                        vueInstanse.month = row.month;
                                        vueInstanse.getDatesArr(row.daysstatus);
                                        vueInstanse.modal = true;
                                    }
                                }
                            },
                            onlineDate
                        );
                    }
                }
            ],
            tableData: [],
        },
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("reportForm.ascriptionUser"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.onlineDaysAndTotalDays"),
                        vRoot.$t("reportForm.onlineRate"),
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.username);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.onlineDaysAndTotalDays);
                    itemArr.push(item.onlineRate);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.monthlyVehicleOnlineRate') + ' ' + this.queryDateRange,
                    data: data,
                }
                new XlsxCls(options).exportExcel();



            },
            getUserName: function(deviceid) {
                var userName = "";
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid === deviceid) {
                            userName = group.username;
                        }
                    }
                });
                return userName;
            },
            onClickQuery: function() {
                if (this.checkedDevice.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.loading = true;
                var url = myUrls.reportDeviceOnlineMonth(),
                    me = this;
                var data = {
                    deviceids: [],
                    offset: timeDifference,
                    year: this.yearMonth.getFullYear(),
                    month: this.yearMonth.getMonth() + 1,
                }
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            data.deviceids.push(group.deviceid);
                        } else {
                            isNull = true;
                        }
                    }
                });
                if (data.deviceids.length === 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    me.queryDateRange = me.yearMonth.getFullYear() + '-' + me.yearMonth.getMonth() + 1;
                    if (respData.status === 0) {
                        me.daycount = respData.daycount;
                        me.tableData = me.getTableData(respData.records, data.year, data.month);
                    }
                })
            },
            //得到这个月的第一天是是星期几
            getTheMonthFirstDayWeek: function() {
                return new Date(this.year, this.month - 1, 1).getDay();
            },
            // 得到这个月有多少天
            getTheMonthDays: function() {
                var year = this.month == 12 ? this.year + 1 : this.year;
                var month = this.month == 12 ? 1 : this.month;
                return new Date(new Date(year, month, 1) - 1).getDate();
            },
            // 得到上个月的最后一天
            getPrevMonthLastDate: function() {
                return new Date(new Date(this.year, this.month - 1, 1) - 1).getDate();
            },
            getDatesArr: function(daysstatus) {
                var datesArr = [];
                var weekNum = this.getTheMonthFirstDayWeek();
                var prevMonthDate = this.getPrevMonthLastDate();
                var theDates = this.getTheMonthDays();

                while (weekNum--) {
                    datesArr.unshift({ day: prevMonthDate--, isTheMonth: false });
                }
                var d = 1
                while (theDates--) {
                    var isActive = daysstatus[d - 1] === 1;
                    datesArr.push({ day: d, isTheMonth: true, isActive: isActive });
                    d++;
                }
                var count = 1;
                while (datesArr.length < 42) {
                    datesArr.push({ day: count++, isTheMonth: false });
                }
                this.datesArr = datesArr;
            },
            getTableData: function(records, year, month) {
                var tableData = [];
                var me = this;
                records.forEach(function(item) {
                    var tableItem = {};
                    var onlineCount = 0;
                    tableItem.deviceid = item.deviceid;
                    item.daysstatus.forEach(function(item, idx) {
                        var isOnline = item == 0 ? false : true;
                        if (isOnline) {
                            onlineCount++;
                            tableItem[String(++idx)] = '1';
                        } else {
                            tableItem[String(++idx)] = '0';
                        }
                    })
                    var onlineRate = (onlineCount / item.daysstatus.length) * 100;
                    tableItem['onlinecount'] = onlineCount;
                    tableItem['onlineRate'] = onlineRate.toFixed(2) + '%';
                    tableItem.daysstatus = item.daysstatus;
                    tableItem.username = me.getUserName(tableItem.deviceid);
                    tableItem.onlineDaysAndTotalDays = onlineCount + "/" + item.daysstatus.length;
                    tableItem.devicename = vstore.state.deviceInfos[tableItem.deviceid].devicename;
                    tableItem.year = year;
                    tableItem.month = month;
                    tableData.push(tableItem);

                });
                return tableData;
            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 125;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            this.queryDevicesTree();
            window.onresize = function() {
                me.calcTableHeight();
            };
        },
        created: function() {
            this.checkedDevice = [];
        },
    })
}

//新增车辆
function newEquipmentReport() {
    new Vue({
        el: "#new-equipment-report",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            columns: [{
                key: 'index',
                title: '#',
                width: 80,
            }, {
                title: vRoot.$t("alarm.devName"),
                key: 'devicename',
            }, {
                title: vRoot.$t("alarm.devNum"),
                key: 'deviceid'
            }, {
                title: vRoot.$t("user.devType"),
                key: 'devtype'
            }, {
                title: vRoot.$t("bgMgr.addTime"),
                key: 'createtimestr'
            }, {
                title: vRoot.$t("bgMgr.creater"),
                render: function(h, params) {
                    var creater = params.row.creater;
                    return h('Poptip', {
                        props: {
                            confirm: false,
                            // title: '上级信息',
                        },
                        style: {
                            marginRight: '5px',
                        },
                    }, [
                        h('Button', {
                            props: {
                                type: 'info',
                                size: 'small'
                            },
                            on: {
                                click: function() {

                                    var url = myUrls.queryParents();
                                    var data = {
                                        currentuser: creater
                                    }
                                    utils.sendAjax(url, data, function(resp) {
                                        var createrrecords = [];
                                        var records = resp.records;
                                        records.forEach(function(item) {
                                            createrrecords.push(h('div', {}, item.username + '(' + utils.getUserTypeDesc(item.usertype) + ')'))
                                        });
                                        params.row.createrrecords = createrrecords;
                                    })
                                }
                            }
                        }, creater),
                        h(
                            'div', {
                                slot: 'content',
                                attrs: {
                                    slot: "content"
                                }
                            }, params.row.createrrecords
                        )
                    ]);
                }
            }],
            tableData: [],
            tableHeight: 300,
            days: '7',
            recordRankingArr: [],
            total: 0,
            currentIndex: 1,
        },
        watch: {
            days: function() {
                this.queryAddDevices();
            }
        },
        methods: {
            changePage: function(index) {
                document.body.click()
                var offset = index * 10;
                var start = (index - 1) * 10;
                this.currentPageIndex = index;
                this.tableData = this.allTableData.slice(start, offset);

            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.tableHeight = wHeight - 360;
            },
            setRecordRankingArr: function(recordRanking) {
                var recordRankingArr = [];
                for (var key in recordRanking) {
                    recordRankingArr.push({
                        creater: key,
                        count: recordRanking[key]
                    })
                }
                recordRankingArr.sort(function(a, b) {
                    return b.count - a.count;
                });
                if (recordRankingArr.length > 5) {
                    recordRankingArr.length = 5;
                }
                this.recordRankingArr = recordRankingArr;
            },
            queryAddDevices: function() {
                var me = this;
                var url = myUrls.queryAddDevices();
                var dates = this.getLatestDate();
                var data = {
                    offset: timeDifference,
                    days: Number(this.days),
                };
                this.loading = true;
                this.allTableData = [];
                this.tableData = [];
                this.recordRankingArr = [];
                this.currentIndex = 1;
                this.total = 0;
                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    var devices = respData.devices;
                    var seriesData = [];
                    var tableData = [];
                    var recordRanking = {};
                    if (respData.status === 0 && devices.length) {
                        devices.forEach(function(dev, idx) {
                            var creater = dev.creater;
                            if (recordRanking[creater]) {
                                recordRanking[creater] = recordRanking[creater] + 1;
                            } else {
                                recordRanking[creater] = 1;
                            }
                            tableData.push({
                                devtype: me.getDevType(dev.devicetype),
                                createtimestr: DateFormat.longToLocalDateTimeStr(dev.createtime),
                                devicename: dev.devicename,
                                deviceid: dev.deviceid,
                                creater: creater,
                                createtime: dev.createtime,
                                createrrecords: [],
                            })
                        });
                        tableData.sort(function(a, b) {
                            return b.createtime - a.createtime;
                        });
                        tableData.forEach(function(item, idx) {
                            item.index = idx + 1;
                        });
                        me.total = tableData.length;
                        me.allTableData = tableData;
                        if (me.total > 10) {
                            me.tableData = tableData.slice(0, 10);
                        } else {
                            me.tableData = tableData;
                        }
                        me.setRecordRankingArr(recordRanking);
                        dates.forEach(function(date) {
                            var count = 0;
                            devices.forEach(function(dev) {
                                var dateStr = DateFormat.longToDateStr(dev.createtime, timeDifference);
                                if (date == dateStr) {
                                    count++;
                                }
                            })
                            seriesData.push(count);
                        });
                        me.charts.setOption(me.getChartsOption(dates, seriesData), true);
                    }
                }, function() {
                    me.loading = false;
                });
            },
            getDevType: function(devicetype) {
                var devType = "";
                var item = vstore.state.deviceTypes[devicetype];
                var label = item.typename;
                if (item.remark) {
                    label += "(" + item.remark + ")";
                }
                devType = label;
                return devType;
            },
            initCharts: function() {
                this.charts = echarts.init(document.getElementById('charts'));
                this.charts.setOption(this.getChartsOption(this.getLatestDate(), []), true);
            },
            getChartsOption: function(dates, seriesData) {
                return {
                    title: {
                        text: ""
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    // legend: {
                    //     data: ['新增设备']
                    // },
                    grid: {
                        top: '8%',
                        left: '4%',
                        right: '4%',
                        bottom: '4%',
                        containLabel: true
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: dates
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                        name: '新增设备',
                        type: 'line',
                        stack: '总量',
                        data: seriesData,
                        smooth: true,
                    }]
                };
            },
            getLatestDate: function() {
                var days = Number(this.days);
                var dates = [];
                var firstDate = DateFormat.format(new Date(Date.now() - (days - 1) * 24 * 3600 * 1000), 'yyyy-MM-dd');
                for (var i = 0; i < days; i++) {
                    var date = DateFormat.addDay(new Date(firstDate), i);
                    var dateStr = DateFormat.format(date, 'yyyy-MM-dd');
                    dates.push(dateStr);
                }
                return dates;
            },
        },
        mounted: function() {
            var me = this;
            this.allTableData = [];
            this.initCharts();
            this.queryAddDevices();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
                me.charts.resize();
            }
        }
    })
}

function deviceTypeDistribution(groupslist) {
    new Vue({
        el: "#distribution",
        methods: {
            getChartsOption: function(data) {
                var option = {
                    title: {
                        text: vRoot.$t("reportForm.deviceTypeDistribution"),
                        bottom: 'auto'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: function(name) {
                            return name.data.name + '<br/>' + name.data.value + '<br/>' + name.data.remark;
                        }
                    },
                    legend: {
                        type: 'scroll',
                        orient: 'vertical',
                        right: 10,
                        top: 20,
                        bottom: 20,
                        data: data.legendData,
                        // orient: 'vertical',
                        // left: 'right',
                    },
                    grid: {
                        top: 5,
                        left: 5,
                        right: 5,
                        bottom: 5,
                    },
                    series: [{
                        type: 'pie',
                        radius: '70%',
                        data: data.seriesData,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }]
                };
                return option
            },
            getSeriesData: function() {
                var totalDeviceCountObj = {};
                groupslist.forEach(function(group) {
                    group.devices.forEach(function(device) {
                        var devicetype = device.devicetype;
                        if (totalDeviceCountObj[devicetype]) {
                            totalDeviceCountObj[devicetype] += 1;
                        } else {
                            totalDeviceCountObj[devicetype] = 1;
                        }
                    });
                });

                var seriesData = [];
                var legendData = [];

                for (var key in totalDeviceCountObj) {
                    var nameObj = this.getDevType(key);
                    seriesData.push({
                        value: totalDeviceCountObj[key],
                        name: nameObj.name,
                        remark: nameObj.remark
                    })
                }

                seriesData.sort(function(a, b) {
                    return b.value - a.value;
                })

                seriesData.forEach(function(series) {
                    legendData.push(series.name);
                });



                return {
                    seriesData: seriesData,
                    legendData: legendData,
                };
            },
            getDevType: function(devicetype) {
                var item = vstore.state.deviceTypes[devicetype];
                var typename = item.typename;
                var remark = "";
                if (item) {
                    if (item.remark) {
                        remark = item.remark;
                    }
                }


                return {
                    name: typename,
                    remark: remark,
                };
            },
            initCharts: function() {
                this.charts = echarts.init(document.getElementById('distribution'));
                this.charts.setOption(this.getChartsOption(this.getSeriesData()), true);
            },
        },
        mounted: function() {
            var me = this;
            this.initCharts();
            window.onresize = function() {
                me.charts.resize();
            }
        },
    })
}


function onlineStatisticsDay() {
    new Vue({
        el: "#online-statistics-day",
        data: {
            isSpin: false,
        },
        methods: {
            queryOnlineStatisticsDay: function() {
                var me = this;
                var url = myUrls.queryOnlineStatisticsDay();
                var data = {};
                me.isSpin = true;
                utils.sendAjax(url, data, function(respData) {
                    me.isSpin = false;
                    if (respData.status == 0) {
                        me.initCharts(respData.records);
                    } else {
                        me.initCharts([]);
                    }
                }, function() {
                    me.initCharts([]);
                    me.isSpin = false;
                    me.$Message.error(vRoot.$t("monitor.queryFail"));
                })
            },
            getChartsOption: function(dates, seriesData) {
                return {
                    title: {
                        text: vRoot.$t("reportForm.onlineStatisticsDay")
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    // legend: {
                    //     data: ['新增设备']
                    // },
                    grid: {
                        top: '8%',
                        left: '4%',
                        right: '4%',
                        bottom: '4%',
                        containLabel: true
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: dates
                    },
                    yAxis: {
                        type: 'value',
                        min: "dataMin"
                    },
                    series: [{
                        name: vRoot.$t("reportForm.onlineEquipment"),
                        type: 'line',
                        stack: '总量',
                        data: seriesData,
                        smooth: true,

                    }]
                };
            },
            initCharts: function(records) {
                var me = this;
                var datas = [];
                var seriesData = [];

                records.forEach(function(record) {
                    datas.push(record.statisticsday);
                    seriesData.push(record.count);
                });

                this.charts = echarts.init(document.getElementById('statistics-charts'));
                this.charts.setOption(this.getChartsOption(datas, seriesData), true);

                window.onresize = function() {
                    me.charts.resize();
                }
            }
        },
        mounted: function() {

            this.queryOnlineStatisticsDay();
        },
    })
}

function timeWeightConsumption(groupslist) {
    vueInstanse = new Vue({
        el: "#time-weight-consumption",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            groupslist: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), type: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 100 },
                { title: vRoot.$t('reportForm.date'), key: 'updatetimeStr', sortable: true, width: 160 },
                { title: vRoot.$t('reportForm.totalMileage') + '(km)', key: 'totaldistance', width: 150 },
                { title: vRoot.$t('reportForm.weight') + '(kg)', key: 'weight', width: 100 },
                { title: vRoot.$t('reportForm.speed'), key: 'speed', width: 80 },
                { title: vRoot.$t('reportForm.status'), key: 'strstatus' },
                { title: vRoot.$t('reportForm.loadstatus'), key: 'loadstatusStr' },
                {
                    title: vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                    render: function(h, params) {
                        var row = params.row;
                        var callat = row.callat.toFixed(5);
                        var callon = row.callon.toFixed(5);

                        if (callat && callon) {
                            if (row.address == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(callon, callat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.records[params.index].address = resp.address;
                                                    LocalCacheMgr.setAddress(callon, callat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, callon + "," + callat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.address,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, callon + "," + callat)
                                ]);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
            ],
            tableData: [],
            recvtime: [],
            weights: [],
            veo: [],
            distance: [],
            loadstatuss: [],
            currentIndex: 1,
        },
        mixins: [reportMixin],
        methods: {
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t('reportForm.date'),
                        vRoot.$t('reportForm.totalMileage') + '(km)',
                        vRoot.$t('reportForm.weight') + '(kg)',
                        vRoot.$t('reportForm.speed'),
                        vRoot.$t('reportForm.status'),
                        vRoot.$t('reportForm.loadstatus'),
                        vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    var callon = item.callon.toFixed(5);
                    var callat = item.callat.toFixed(5);
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.updatetimeStr);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.weight);
                    itemArr.push(item.speed);
                    itemArr.push(item.strstatus);
                    itemArr.push(item.loadstatusStr);
                    itemArr.push(callon + ',' + callat);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.timeWeightConsumption'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();


            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentPageIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            charts: function() {
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var weight = vRoot.$t('reportForm.weight');
                var status = vRoot.$t('reportForm.status');
                var option = {
                    title: {
                        text: time + '/' + weight,
                        x: 'center',
                        textStyle: {
                            fontSize: 12,
                            fontWeight: 'bolder',
                            color: '#333'
                        }
                    },
                    grid: {
                        x: 50,
                        y: 40,
                        x2: 50,
                        y2: 40
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName && v[i].seriesName != time) {
                                    if (v[i].seriesName == weight) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'kg<br/>';
                                    } else if (v[i].seriesName == dis) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else {
                                        data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, weight],
                        x: 'left'
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        //fillerColor:'rgb(244,129,38,0.8)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: weight + '/' + speed,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: dis,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.veo
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distance
                        }, {
                            smooth: true,
                            name: weight,
                            type: 'line',
                            symbol: 'none',
                            color: '#C1232B',
                            data: this.weights
                        },
                        {
                            smooth: true,
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates
                        },
                        {
                            smooth: true,
                            name: vRoot.$t('reportForm.loadstatus'),
                            type: 'line',
                            symbol: 'none',
                            data: this.loadstatuss
                        },
                    ]
                };

                this.chartsIns.setOption(option, true);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 400;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") { return };
                var self = this;
                if (this.isSelectAll === null) {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                    return;
                };
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportWeightTime(), data, function(resp) {
                    self.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {
                            var records = [],
                                weights = [],
                                veo = [],
                                distance = [],
                                recvtime = [],
                                loadstatuss = [],
                                devStates = [];
                            var fisstDistance = 0;
                            resp.records.forEach(function(item, index) {
                                records = item.records;
                                var independent = item.independent === 0;
                                records.forEach(function(record, index) {
                                    if (index == 0) {
                                        fisstDistance = record.totaldistance;
                                    }

                                    var callon = record.callon.toFixed(5);
                                    var callat = record.callat.toFixed(5);
                                    var address = LocalCacheMgr.getAddress(callon, callat);
                                    if (address != null) {
                                        record.address = address;
                                    } else {
                                        record.address = null;

                                    }
                                    var ad0 = record.ad0;
                                    var ad1 = record.ad1;
                                    if (ad0 < 0) {
                                        ad0 = 0;
                                    };
                                    if (ad1 < 0) {
                                        ad1 = 0;
                                    };
                                    record.ad0 = ad0 / 100;
                                    record.ad1 = ad1 / 100;
                                    if (independent) {
                                        record.oil = record.ad0 + record.ad1;
                                    } else {
                                        record.oil = record.ad0;
                                    }
                                    record.loadstatusStr = utils.getloadstatusStr(record.loadstatus);
                                    loadstatuss.push(record.loadstatusStr);
                                    record.weight = (record.weight / 10);
                                    record.updatetimeStr = DateFormat.longToLocalDateTimeStr(record.updatetime);
                                    record.devicename = vstore.state.deviceInfos[self.queryDeviceId].devicename;
                                    weights.push(record.weight);
                                    veo.push((record.speed / 1000).toFixed(2));
                                    record.totaldistance = ((record.totaldistance - fisstDistance) / 1000).toFixed(2);
                                    distance.push(record.totaldistance);
                                    recvtime.push(record.updatetimeStr);
                                    devStates.push(record.strstatus);
                                });
                            });

                            self.veo = veo;
                            self.weights = weights;
                            self.distance = distance;
                            self.recvtime = recvtime;
                            self.records = records;
                            self.devStates = devStates;
                            self.loadstatuss = loadstatuss;
                            self.total = records.length;
                            records.sort(function(a, b) {
                                return b.updatetime - a.updatetime;
                            })
                            self.currentPageIndex = 1;
                            self.tableData = records.slice(0, 20);
                            self.charts();
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                }, function() {
                    self.loading = false;
                });
            },
            onSortChange: function(column) {

            }
        },
        mounted: function() {
            this.groupslist = groupslist;
            this.myChart = null;
            this.records = [];
            this.disMin = 0;
            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.charts();
        }
    });
}


function weightSummary(groupslist) {
    vueInstanse = new Vue({
        el: "#weight-summary",
        i18n: utils.getI18n(),
        data: {
            isSpin: false,
            loading: false,
            groupslist: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), type: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename' },
                { title: vRoot.$t('reportForm.date'), key: 'statisticsday', sortable: true },
                { title: isZh ? '空车时长' : 'Empty Duration', key: 'emptyDurationTime' },
                { title: isZh ? '空车里程' : 'Empty Mileage', key: 'emptyDurationDist' },
                { title: isZh ? '半载时长' : 'Half Load Duration', key: 'halfLoadDurationTime' },
                { title: isZh ? '半载里程' : 'Half Load Mileage', key: 'halfLoadDurationDist' },
                { title: isZh ? '超载时长' : 'Overload Duration', key: 'overDurationTime' },
                { title: isZh ? '超载里程' : 'Overload Mileage', key: 'overDurationDist' },
                { title: isZh ? '满载时长' : 'Full Load Duration', key: 'fullDurationTime' },
                { title: isZh ? '满载里程' : 'Full Load Mileage', key: 'fullDurationDist' },
                { title: isZh ? '装载时长' : 'Loading Duration', key: 'loadingDurationTime' },
                { title: isZh ? '装载里程' : 'Loading Mileage', key: 'loadingDurationDist' },
                { title: isZh ? '卸载时长' : 'Unloading Duration', key: 'unloadDurationTime' },
                { title: isZh ? '卸载里程' : 'Unloading Mileage', key: 'unloadDurationDist' },
            ],
            tableData: [],
            seriesData: [],

            activeTab: 'tabTotal',
            allWeightColumns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 100,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function(e) {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    vueInstanse.activeTab = "tabDetail";
                                    editObject = params.row;
                                    vueInstanse.getDetailTableData(params.row.deviceid, params.row.dailyrecords);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, isZh ? "[ 明细 ]" : "[ Details ]")
                    }
                },
                { title: vRoot.$t('alarm.devName'), key: 'devicename' },
                { title: isZh ? '空车时长' : 'Empty Duration', key: 'emptyDurationTime' },
                { title: isZh ? '空车里程' : 'Empty Mileage', key: 'emptyDurationDist' },
                { title: isZh ? '半载时长' : 'Half Load Duration', key: 'halfLoadDurationTime' },
                { title: isZh ? '半载里程' : 'Half Load Mileage', key: 'halfLoadDurationDist' },
                { title: isZh ? '超载时长' : 'Overload Duration', key: 'overDurationTime' },
                { title: isZh ? '超载里程' : 'Overload Mileage', key: 'overDurationDist' },
                { title: isZh ? '满载时长' : 'Full Load Duration', key: 'fullDurationTime' },
                { title: isZh ? '满载里程' : 'Full Load Mileage', key: 'fullDurationDist' },
                { title: isZh ? '装载时长' : 'Loading Duration', key: 'loadingDurationTime' },
                { title: isZh ? '装载里程' : 'Loading Mileage', key: 'loadingDurationDist' },
                { title: isZh ? '卸载时长' : 'Unloading Duration', key: 'unloadDurationTime' },
                { title: isZh ? '卸载里程' : 'Unloading Mileage', key: 'unloadDurationDist' },
            ],
            allWeightTableData: [],
        },
        mixins: [treeMixin],
        methods: {
            exportData: function() {

                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            isZh ? '空车时长' : 'Empty Duration',
                            isZh ? '空车里程' : 'Empty Mileage',
                            isZh ? '半载时长' : 'Half Load Duration',
                            isZh ? '半载里程' : 'Half Load Mileage',
                            isZh ? '超载时长' : 'Overload Duration',
                            isZh ? '超载里程' : 'Overload Mileage',
                            isZh ? '满载时长' : 'Full Load Duration',
                            isZh ? '满载里程' : 'Full Load Mileage',
                            isZh ? '装载时长' : 'Loading Duration',
                            isZh ? '装载里程' : 'Loading Mileage',
                            isZh ? '卸载时长' : 'Unloading Duration',
                            isZh ? '卸载里程' : 'Unloading Mileage',
                        ]
                    ];
                    this.allWeightTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.emptyDurationTime);
                        itemArr.push(item.emptyDurationDist);
                        itemArr.push(item.halfLoadDurationTime);
                        itemArr.push(item.halfLoadDurationDist);
                        itemArr.push(item.overDurationTime);
                        itemArr.push(item.overDurationDist);
                        itemArr.push(item.fullDurationTime);
                        itemArr.push(item.fullDurationDist);
                        itemArr.push(item.loadingDurationTime);
                        itemArr.push(item.loadingDurationDist);
                        itemArr.push(item.unloadDurationTime);
                        itemArr.push(item.unloadDurationDist);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.weightSummary'),
                        data: data,
                    }
                    new XlsxCls(options).exportExcel();

                } else {


                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t('reportForm.date'),
                            isZh ? '空车时长' : 'Empty Duration',
                            isZh ? '空车里程' : 'Empty Mileage',
                            isZh ? '半载时长' : 'Half Load Duration',
                            isZh ? '半载里程' : 'Half Load Mileage',
                            isZh ? '超载时长' : 'Overload Duration',
                            isZh ? '超载里程' : 'Overload Mileage',
                            isZh ? '满载时长' : 'Full Load Duration',
                            isZh ? '满载里程' : 'Full Load Mileage',
                            isZh ? '装载时长' : 'Loading Duration',
                            isZh ? '装载里程' : 'Loading Mileage',
                            isZh ? '卸载时长' : 'Unloading Duration',
                            isZh ? '卸载里程' : 'Unloading Mileage',
                        ]
                    ];
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.statisticsday);
                        itemArr.push(item.emptyDurationTime);
                        itemArr.push(item.emptyDurationDist);
                        itemArr.push(item.halfLoadDurationTime);
                        itemArr.push(item.halfLoadDurationDist);
                        itemArr.push(item.overDurationTime);
                        itemArr.push(item.overDurationDist);
                        itemArr.push(item.fullDurationTime);
                        itemArr.push(item.fullDurationDist);
                        itemArr.push(item.loadingDurationTime);
                        itemArr.push(item.loadingDurationDist);
                        itemArr.push(item.unloadDurationTime);
                        itemArr.push(item.unloadDurationDist);
                        data.push(itemArr);
                    });

                    var options = {
                        title: vRoot.$t('reportForm.loadingStatusDetails') + ' - ' + editObject.deviceid,
                        data: data,
                    }
                    new XlsxCls(options).exportExcel();
                }



            },
            getDetailTableData: function(deviceid, records) {
                var tableData = [];
                records.forEach(function(dayItem) {
                    var item = { deviceid: deviceid };
                    item.statisticsday = dayItem.statisticsday;
                    item.devicename = vstore.state.deviceInfos[deviceid].devicename;
                    dayItem.records.forEach(function(totalRecord) {
                        switch (totalRecord.loadstatus) {
                            case 0:
                                item.emptyDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                item.emptyDurationDist = totalRecord.durationdistance;
                                item.durationtime0 = totalRecord.durationtime / 1000 / 60;
                                break;
                            case 1:
                                item.halfLoadDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                item.halfLoadDurationDist = totalRecord.durationdistance;
                                item.durationtime1 = totalRecord.durationtime / 1000 / 60;
                                break;
                            case 2:
                                item.overDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                item.overDurationDist = totalRecord.durationdistance;
                                item.durationtime2 = totalRecord.durationtime / 1000 / 60;
                                break;
                            case 3:
                                item.fullDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                item.fullDurationDist = totalRecord.durationdistance;
                                item.durationtime3 = totalRecord.durationtime / 1000 / 60;
                                break;
                            case 4:
                                item.loadingDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                item.loadingDurationDist = totalRecord.durationdistance;
                                item.durationtime4 = totalRecord.durationtime / 1000 / 60;
                                break;
                            case 5:
                                item.unloadDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                item.unloadDurationDist = totalRecord.durationdistance;
                                item.durationtime5 = totalRecord.durationtime / 1000 / 60;
                                break;
                        }
                    });
                    tableData.push(item);
                });
                this.tableData = tableData;
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            onCurrentChange: function(current) {
                var seriesData = [];
                var titleText = '';
                if (current.statisticsday) {
                    titleText = (isZh ? '载重时长-' : 'Loading Duration-') + current.deviceid + '-' + current.statisticsday;
                } else {
                    titleText = (isZh ? '载重时长-' : 'Loading Duration-') + current.deviceid;
                }
                for (var i = 0; i < 6; i++) {
                    var title = utils.getloadstatusStr(i) + (isZh ? '时长' : 'Duration');
                    seriesData.push({
                        value: current['durationtime' + i],
                        name: title
                    });
                }
                this.seriesData = seriesData;
                this.charts(titleText);
            },
            charts: function(title) {
                var option = {
                    title: {
                        text: title,
                        bottom: 'auto'
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'right',
                    },
                    // grid: {
                    //     top: 5,
                    //     left: 20,
                    //     right: 5,
                    //     bottom: 5,
                    // },
                    series: [{
                        type: 'pie',
                        radius: '70%',
                        data: this.seriesData,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }]
                };;
                this.chartsIns.setOption(option, true);
            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 570;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length) {
                    var self = this;
                    var data = {
                        // username: vstore.state.userName,
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        devices: deviceids,
                    };
                    this.loading = true;
                    this.activeTab = 'tabTotal';
                    utils.sendAjax(myUrls.reportWeightSummary(), data, function(resp) {
                        self.loading = false;
                        console.log('resp', resp);
                        if (resp.status == 0) {
                            if (resp.records) {
                                var tableData = [];

                                resp.records.forEach(function(deyItem, index) {
                                    var totalObj = {
                                        index: index + 1,
                                        deviceid: deyItem.deviceid,
                                        devicename: vstore.state.deviceInfos[deyItem.deviceid].devicename,
                                        dailyrecords: deyItem.dailyrecords,
                                    }
                                    deyItem.totalrecords.forEach(function(totalRecord) {
                                        switch (totalRecord.loadstatus) {
                                            case 0:
                                                totalObj.emptyDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                                totalObj.emptyDurationDist = totalRecord.durationdistance;
                                                totalObj.durationtime0 = totalRecord.durationtime / 1000 / 60;
                                                break;
                                            case 1:
                                                totalObj.halfLoadDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                                totalObj.halfLoadDurationDist = totalRecord.durationdistance;
                                                totalObj.durationtime1 = totalRecord.durationtime / 1000 / 60;
                                                break;
                                            case 2:
                                                totalObj.overDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                                totalObj.overDurationDist = totalRecord.durationdistance;
                                                totalObj.durationtime2 = totalRecord.durationtime / 1000 / 60;
                                                break;
                                            case 3:
                                                totalObj.fullDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                                totalObj.fullDurationDist = totalRecord.durationdistance;
                                                totalObj.durationtime3 = totalRecord.durationtime / 1000 / 60;
                                                break;
                                            case 4:
                                                totalObj.loadingDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                                totalObj.loadingDurationDist = totalRecord.durationdistance;
                                                totalObj.durationtime4 = totalRecord.durationtime / 1000 / 60;
                                                break;
                                            case 5:
                                                totalObj.unloadDurationTime = utils.timeStampNoSecond(totalRecord.durationtime);
                                                totalObj.unloadDurationDist = totalRecord.durationdistance;
                                                totalObj.durationtime5 = totalRecord.durationtime / 1000 / 60;
                                                break;
                                        }
                                    });

                                    tableData.push(totalObj);

                                });

                                self.allWeightTableData = tableData;
                                setTimeout(function name() {
                                    self.$refs.totalTable.$refs.tbody.clickCurrentRow(0);
                                }, 800);

                            } else {
                                self.$Message.error(self.$t("reportForm.noRecord"));
                            }
                        } else {
                            self.$Message.error(resp.cause);
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }

            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            onSortChange: function(column) {

            }
        },
        mounted: function() {
            this.myChart = null;
            this.records = [];
            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.charts(isZh ? "载重时长" : 'Load Duration');
            this.queryDevicesTree();
        }
    });
}

function timeOilConsumption(groupslist) {
    vueInstanse = new Vue({
        el: "#time-oil-consumption",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            groupslist: [],
            isShowCard: false,
            contentString: "",
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 160 },
                { title: vRoot.$t('reportForm.updateTime'), key: 'updatetimeStr', sortable: true, width: 160 },
                { title: vRoot.$t('reportForm.arrivedtimeStr'), key: 'arrivedtimeStr', sortable: true, width: 160 },
                { title: vRoot.$t('reportForm.totalMileage') + '(km)', key: 'totaldistance', width: 110 },
                { title: vRoot.$t('reportForm.totalOil'), key: 'totalad', width: 100 },
                { title: vRoot.$t('reportForm.notRunTotalad'), key: 'totalnotrunningad', width: 100 },
                { title: vRoot.$t('reportForm.speed'), key: 'speed', width: 110 },
                { title: vRoot.$t('reportForm.reissue'), key: 'reissue', width: 120 },
                { title: vRoot.$t('reportForm.status'), key: 'strstatus', width: 300 },
                {
                    title: vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                    width: 210,
                    render: function(h, params) {
                        var row = params.row;
                        var callat = row.callat.toFixed(5);
                        var callon = row.callon.toFixed(5);

                        if (callat && callon) {
                            if (row.address == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(callon, callat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.records[params.index].address = resp.address;
                                                    LocalCacheMgr.setAddress(callon, callat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, callon + "," + callat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.address,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, callon + "," + callat)
                                ]);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
            ],
            tableData: [],
            recvtime: [],
            totalad: [],
            veo: [],
            distance: [],
            oil1: [],
            oil2: [],
            oil3: [],
            oil4: [],
            srcad0: [],
            srcad1: [],
            srcad2: [],
            srcad3: [],
            altitudes: [],
            voltages: [],
            devReissue: [],
            currentIndex: 1,
            dateCharts: DateFormat.format(new Date(), 'yyyy-MM-dd hh:mm:ss'),
            oilCount: 0,
            oilColumns: [{
                    // title: isZh ? '编号' : 'index',
                    type: 'index',
                    width: 70
                },
                {
                    title: isZh ? '油路' : 'Box Index',
                    key: 'oilindex',
                    option: oilIndexLabel,
                    width: 120,
                    editable: true
                }, {
                    width: 100,
                    key: 'oilstate',
                    title: (isZh ? '状态' : 'Status'),
                    option: [{ label: isZh ? '加油' : 'Refuel', value: '1' }, { label: isZh ? '漏油' : 'Leak', value: '-1' }],
                    editable: true
                }, {
                    title: (isZh ? '油量' : 'Fuel Volume') + '(L)',
                    key: 'oilVolume',
                    width: 100,
                }, {
                    title: (isZh ? '开始油量' : 'Start Fuel Volume') + '(L)',
                    width: 110,
                    key: 'soil',
                    input: 'number',
                    editable: true,
                }, {
                    title: (isZh ? '结束油量' : 'End Fuel Volume') + '(L)',
                    key: 'eoil',
                    input: 'number',
                    width: 110,
                    editable: true,
                }, {
                    title: isZh ? '开始时间' : 'Begin Time',
                    key: 'begintimeStr',
                    width: 165,
                    editable: true,
                }, {
                    title: isZh ? '结束时间' : 'End Time',
                    key: 'endtimeStr',
                    width: 165,
                    editable: true,
                }, {
                    title: isZh ? '备注' : 'Marker',
                    width: 185,
                    key: 'marker',
                    input: 'text',
                    editable: true,
                }, {
                    title: isZh ? '操作' : 'action',
                    width: 185,
                    key: 'handle',
                    handle: ['edit', 'delete', 'map'],
                    render: function(h) {}
                },
                {
                    title: vRoot.$t('reportForm.saddress'),
                    width: 300,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.slat ? row.slat.toFixed(5) : null;
                        var lon = row.slon ? row.slon.toFixed(5) : null;
                        if (lat && lon) {
                            if (row.saddress == null) {
                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    row.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('span', {}, row.saddress);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
                { title: isZh ? '距离(米)' : 'Distance(m)', key: 'distance', width: 100 },
                { title: isZh ? '平均速度(km/h)' : 'Average speed (km / h)', key: 'avgspeed', width: 140 },
                { title: isZh ? '时长' : 'Duration', key: 'durationStr', width: 110 },
                { title: isZh ? '阈值(L)' : 'Threshold', key: 'threshold', width: 100 },
                { title: isZh ? '人工编辑' : 'Manual editing', key: 'mauneditStr', width: 100 },
            ],
            oilTable: [],
            cloneDataList: [],
            trackDetailModal: false,
            tabActive: 'oil'
        },
        mixins: [reportMixin],
        methods: {
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('oil-details-map');
            },
            queryTracks: function(row) {
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: DateFormat.longToLocalDateTimeStr(row.begintime),
                        endtime: DateFormat.longToLocalDateTimeStr(row.endtime),
                        interval: 5,
                        timezone: timeDifference
                    };
                utils.sendAjax(url, data, function(respData) {

                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.trackDetailModal = true;
                            utils.markersAndLineLayerToMap(me, records);
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            exportData: function() {

                if (this.tabActive == 'oil') {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            isZh ? '油路' : 'Box Index',
                            (isZh ? '状态' : 'Status'),
                            (isZh ? '油量' : 'Fuel Volume') + '(L)',
                            (isZh ? '开始油量' : 'Start Fuel Volume') + '(L)',
                            (isZh ? '结束油量' : 'End Fuel Volume') + '(L)',
                            isZh ? '开始时间' : 'Begin Time',
                            isZh ? '结束时间' : 'End Time',
                            isZh ? '备注' : 'Marker',
                            vRoot.$t('reportForm.saddress'),
                            isZh ? '距离(米)' : 'Distance(m)',
                            isZh ? '平均速度(km/h)' : 'Average speed (km / h)',
                            isZh ? '时长' : 'Duration',
                            isZh ? '阈值(L)' : 'Threshold',
                            isZh ? '人工编辑' : 'Manual editing',
                        ]
                    ];
                    this.oilTable.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.oilindexStr);
                        itemArr.push(item.oilstateStr);
                        itemArr.push(item.oilVolume);
                        itemArr.push(item.soil);
                        itemArr.push(item.eoil);
                        itemArr.push(item.begintimeStr);
                        itemArr.push(item.endtimeStr);
                        itemArr.push(item.marker ? item.marker : '');
                        itemArr.push(item.saddress);
                        itemArr.push(item.distance);
                        itemArr.push(item.avgspeed);
                        itemArr.push(item.durationStr);
                        itemArr.push(item.threshold);
                        itemArr.push(item.mauneditStr);

                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.addOrLeakOilList') + '-' + this.queryDeviceId,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();


                } else {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t('reportForm.updateTime'),
                            vRoot.$t('reportForm.arrivedtimeStr'),
                            vRoot.$t('reportForm.totalMileage') + '(km)',
                            vRoot.$t('reportForm.totalOil'),
                            vRoot.$t('reportForm.notRunTotalad'),
                            vRoot.$t('reportForm.speed'),
                            vRoot.$t('reportForm.reissue'),
                            vRoot.$t('reportForm.status'),
                            vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                        ]
                    ];

                    this.records.forEach(function(item, index) {
                        var itemArr = [];
                        var callat = item.callat.toFixed(5);
                        var callon = item.callon.toFixed(5);
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.updatetimeStr);
                        itemArr.push(item.arrivedtimeStr);
                        itemArr.push(item.totaldistance);
                        itemArr.push(item.totalad);
                        itemArr.push(item.totalnotrunningad);
                        itemArr.push(item.speed);
                        itemArr.push(item.reissue);
                        itemArr.push(item.strstatus);
                        itemArr.push(callon + ',' + callat);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.dateOilConsumption") + '-' + this.queryDeviceId,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();
                }
            },
            queryAddOilStatus: function(tracks) {
                tracks.forEach(function(tracks, index) {
                    tracks.index = index;
                });
                var me = this;
                var data = {
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                    oilstate: 99,
                    oilindex: 0
                };
                utils.sendAjax(myUrls.reportOilRecord(), data, function(resp) {
                    self.loading = false;

                    if (resp.status == 0) {
                        if (resp.records) {
                            var oilArr = [];
                            var increaseOil = 0;
                            var reduceOil = 0;
                            resp.records.forEach(function(item) {
                                var index = 1;
                                item.records.forEach(function(record) {
                                    var oilstate = record.oilstate;
                                    if (oilstate == -1 || oilstate == 1) {


                                        var slat = record.slat.toFixed(5);
                                        var slon = record.slon.toFixed(5);
                                        var saddress = LocalCacheMgr.getAddress(slon, slat);
                                        if (saddress != null) {
                                            record.saddress = saddress;
                                        } else {
                                            record.saddress = null;
                                        };

                                        oilIndexLabel.forEach(function(item) {
                                            if (item.value == record.oilindex) {
                                                record.oilindexStr = item.label;
                                            }
                                        })

                                        if (isZh) {
                                            record.oilstateStr = record.oilstate == 1 ? '加油' : '漏油';
                                        } else {
                                            record.oilstateStr = record.oilstate == 1 ? 'Refuel' : 'Leak';
                                        }

                                        record.begintimeStr = '\t' + DateFormat.longToLocalDateTimeStr(record.begintime);
                                        record.endtimeStr = '\t' + DateFormat.longToLocalDateTimeStr(record.endtime);

                                        record.eoil = record.eoil / 100;
                                        record.soil = record.soil / 100;
                                        record.oilstate = String(oilstate);
                                        record.oilindex = String(record.oilindex);
                                        record.editting = false;
                                        record.saving = false;

                                        record.oilVolume = Math.abs(record.eoil - record.soil).toFixed(2);
                                        record.durationStr = (record.duration / 1000 / 3600).toFixed(2);;
                                        if (isZh) {
                                            record.mauneditStr = record.maunedit == 1 ? '是' : '否'
                                        } else {
                                            record.mauneditStr = record.maunedit == 1 ? 'Yes' : 'NO'
                                        }


                                        oilArr.push(record);

                                        index++;
                                    }
                                });
                            });






                            me.oilTable = oilArr;
                            me.cloneDataList = deepClone(oilArr);

                            // var markPoints = utils.calMarkPoint(tracks, resp.records,0);
                            me.markPointData = utils.calMarkPoint(tracks, resp.records[0].records, 0);
                            me.markPointDataOil1 = utils.calMarkPoint(tracks, resp.records[0].records, 1);
                            me.markPointDataOil2 = utils.calMarkPoint(tracks, resp.records[0].records, 2);
                            me.markPointDataOil3 = utils.calMarkPoint(tracks, resp.records[0].records, 3);
                            me.markPointDataOil4 = utils.calMarkPoint(tracks, resp.records[0].records, 4);
                            me.markPointDataOil99 = utils.calMarkPoint(tracks, resp.records[0].records, 99);

                            me.charts();

                        } else {
                            me.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(resp.cause);
                    }
                })
            },
            rowClassName: function(row, index) {
                if (row.maunedit === 1) {
                    return 'demo-table-info-row';
                }
                return '';
            },
            onRowClick: function(row) {
                var me = this;
                this.isShowCard = true;
                this.queryTrackDetail(row, function(resp) {
                    if (resp.track) {
                        me.contentString = JSON.stringify(resp.track);
                    } else {
                        vm.$Message.error(me.$t("reportForm.noRecord"));
                    }
                });
            },

            queryTrackDetail: function(row, callback) {
                var data = {
                    deviceid: this.queryDeviceId,
                    updatetime: row.updatetime,
                    trackid: row.trackid
                }
                var url = myUrls.queryTrackDetail();
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        callback(resp);
                    }
                })
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentPageIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            charts: function() {
                var totoil = vRoot.$t('reportForm.totalOil');
                var notRunTotalad = vRoot.$t('reportForm.notRunTotalad');
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');

                var srcad0 = vRoot.$t('reportForm.srcad0');
                var srcad1 = vRoot.$t('reportForm.srcad1');
                var srcad2 = vRoot.$t('reportForm.srcad2');
                var srcad3 = vRoot.$t('reportForm.srcad3');

                var cotgasus = vRoot.$t('reportForm.oil');
                var status = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t('reportForm.reissue');

                var altitude = vRoot.$t('reportForm.altitude');
                var voltage = vRoot.$t('reportForm.voltage');

                var option = {
                    title: {
                        // text: time + '/' + cotgasus,
                        // x: 'center',
                        // textStyle: {
                        //     fontSize: 12,
                        //     fontWeight: 'bolder',
                        //     color: '#333'
                        // }
                    },
                    grid: {
                        top: 30,
                        left: 60,
                        right: 60,
                        bottom: 40,
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName && v[i].seriesName != time) {
                                    if (v[i].seriesName == dis) {
                                        var currentDistance = v[i].value;
                                        var totalDistance = ((Number(currentDistance) + firstDistance / 1000)).toFixed(2);
                                        data += v[i].seriesName + ' : ' + currentDistance + "km(T:" + totalDistance + 'km)<br/>';

                                    } else if (v[i].seriesName == notRunTotalad || v[i].seriesName == totoil || v[i].seriesName == usoil1 || v[i].seriesName == usoil2 || v[i].seriesName == usoil3 || v[i].seriesName == usoil4) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'L<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else if (v[i].seriesName == altitude) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'm<br/>';
                                    } else if (v[i].seriesName == voltage) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'V<br/>';
                                    } else {
                                        data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, totoil, notRunTotalad, usoil1, usoil2, usoil3, usoil4, srcad0, srcad1, srcad2, srcad3, altitude, voltage],
                        selected: this.selectedLegend,
                        x: 'left',
                        // width: 600,
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        //fillerColor:'rgb(244,129,38,0.8)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: '', //totoil + '/' + speed
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: '', //dis
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.veo
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distance
                        }, {
                            smooth: true,
                            name: totoil,
                            type: 'line',
                            symbol: 'none',
                            color: '#C1232B',
                            data: this.totalad,
                            markPoint: {
                                data: this.markPointData,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: notRunTotalad,
                            type: 'line',
                            symbol: 'none',
                            color: '#E2242B',
                            data: this.notRunTotalad,
                            markPoint: {
                                data: this.markPointDataOil99,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil1,
                            type: 'line',
                            symbol: 'none',
                            color: '#8E388E',
                            data: this.oil1,
                            markPoint: {
                                data: this.markPointDataOil1,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil2,
                            type: 'line',
                            symbol: 'none',
                            color: '#FF4500',
                            data: this.oil2,
                            markPoint: {
                                data: this.markPointDataOil2,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil3,
                            type: 'line',
                            symbol: 'none',
                            color: '#2177C7',
                            data: this.oil3,
                            markPoint: {
                                data: this.markPointDataOil3,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil4,
                            type: 'line',
                            symbol: 'none',
                            color: '#B05432',
                            data: this.oil4,
                            markPoint: {
                                data: this.markPointDataOil4,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: srcad0,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad0
                        },
                        {
                            smooth: true,
                            name: srcad1,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad1
                        },
                        {
                            smooth: true,
                            name: srcad2,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad2
                        },
                        {
                            smooth: true,
                            name: srcad3,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad3
                        },
                        {
                            smooth: true,
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates
                        },
                        {
                            smooth: true,
                            name: reissue,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devReissue
                        },
                        {
                            smooth: true,
                            name: altitude,
                            type: 'line',
                            symbol: 'none',
                            color: '#245779',
                            data: this.altitudes
                        },
                        {
                            smooth: true,
                            name: voltage,
                            type: 'line',
                            symbol: 'none',
                            color: '#8CDCDA',
                            data: this.voltages
                        },
                    ]
                };



                this.chartsIns.setOption(option, true);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 400;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") { return };
                var self = this;
                if (this.isSelectAll === null) {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                    return;
                };

                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportOilTime(), data, function(resp) {
                    self.loading = false;
                    self.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                    self.markPointData = [];
                    if (resp.status == 0) {
                        if (resp.records) {
                            var records = [],
                                totalads = [],
                                notRunTotalad = [],
                                veo = [],
                                distance = [],
                                recvtime = [],
                                oil1 = [],
                                oil2 = [],
                                oil3 = [],
                                oil4 = [],
                                srcad0 = [],
                                srcad1 = [],
                                srcad2 = [],
                                srcad3 = [],
                                devReissue = [],
                                altitudes = [],
                                voltages = [],
                                devStates = [];
                            firstDistance = 0;


                            resp.records.forEach(function(item, index) {
                                records = item.records;
                                // var independent = item.independent === 0;
                                records.forEach(function(record, index) {
                                    if (index == 0) {
                                        firstDistance = record.totaldistance;
                                    };
                                    var callon = record.callon.toFixed(5);
                                    var callat = record.callat.toFixed(5);
                                    var address = LocalCacheMgr.getAddress(callon, callat);
                                    if (address != null) {
                                        record.address = address;
                                    } else {
                                        record.address = null;
                                    }
                                    var totalad = record.totalad;
                                    var totalnotrunningad = record.totalnotrunningad;
                                    var ad0 = record.ad0;
                                    var ad1 = record.ad1;
                                    var ad2 = record.ad2;
                                    var ad3 = record.ad3;
                                    if (ad0 < 0) {
                                        ad0 = 0;
                                    };
                                    if (ad1 < 0) {
                                        ad1 = 0;
                                    };
                                    if (ad2 < 0) {
                                        ad2 = 0;
                                    };
                                    if (ad3 < 0) {
                                        ad3 = 0;
                                    };
                                    record.totalad = totalad / 100;
                                    record.totalnotrunningad = totalnotrunningad / 100;
                                    record.ad0 = ad0 / 100;
                                    record.ad1 = ad1 / 100;
                                    record.ad2 = ad2 / 100;
                                    record.ad3 = ad3 / 100;
                                    record.speed = (record.speed / 1000).toFixed(2);
                                    record.voltage = record.voltage / 100.0;
                                    record.updatetimeStr = DateFormat.longToLocalDateTimeStr(record.updatetime);
                                    record.arrivedtimeStr = DateFormat.longToLocalDateTimeStr(record.arrivedtime);
                                    record.devicename = vstore.state.deviceInfos[self.queryDeviceId].devicename;
                                    totalads.push(record.totalad);
                                    notRunTotalad.push(record.totalnotrunningad);
                                    veo.push(record.speed);
                                    record.totaldistance = ((record.totaldistance - firstDistance) / 1000).toFixed(2);
                                    distance.push(record.totaldistance);
                                    recvtime.push(record.updatetimeStr);
                                    oil1.push(record.ad0);
                                    oil2.push(record.ad1);
                                    oil3.push(record.ad2);
                                    oil4.push(record.ad3);
                                    srcad0.push(record.srcad0);
                                    srcad1.push(record.srcad1);
                                    srcad2.push(record.srcad2);
                                    srcad3.push(record.srcad3);
                                    if (!isZh) {
                                        record.strstatus = record.strstatusen;
                                    }
                                    devStates.push(record.strstatus);
                                    devReissue.push(record.reissue == 0 ? self.$t('header.no') : self.$t('header.yes'));

                                    altitudes.push(record.altitude);
                                    voltages.push(record.voltage);
                                });
                            });


                            self.totalad = totalads;
                            self.notRunTotalad = notRunTotalad;
                            self.veo = veo;
                            self.distance = distance;
                            self.recvtime = recvtime;
                            self.oil1 = oil1;
                            self.oil2 = oil2;
                            self.oil3 = oil3;
                            self.oil4 = oil4;
                            self.srcad0 = srcad0;
                            self.srcad1 = srcad1;
                            self.srcad2 = srcad2;
                            self.srcad3 = srcad3;
                            self.records = records;
                            self.devStates = devStates;
                            self.devReissue = devReissue;
                            self.altitudes = altitudes;
                            self.voltages = voltages;

                            self.queryAddOilStatus(deepClone(records));

                            self.total = records.length;
                            records.sort(function(a, b) {
                                return b.updatetime - a.updatetime;
                            })
                            records.forEach(function(item, index) {
                                item.index = index + 1;
                            })
                            self.currentPageIndex = 1;
                            self.tableData = records.slice(0, 20);



                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                }, function() {
                    self.loading = false;
                })


            },
            addOilRecord: function() {
                var me = this;
                var url = myUrls.addOilRecord();
                var data = {
                    deviceid: this.queryDeviceId,
                    begintime: DateFormat.dateTimeStrToLong(this.dateVal[0] + ' 00:00:00', 0),
                    endtime: DateFormat.dateTimeStrToLong(this.dateVal[1] + ' 23:59:59', 0) //结束时间' ,
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        var oilRecord = resp.oilRecord;
                        oilRecord.oilindex = String(oilRecord.oilindex);
                        oilRecord.oilstate = String(oilRecord.oilstate);
                        oilRecord.saving = false;
                        oilRecord.editting = false;
                        me.cloneDataList.push(oilRecord);
                        me.oilTable.push(deepClone(oilRecord));
                        me.$Message.success(vRoot.$t('message.addSucc'));
                    } else {
                        me.$Message.error(vRoot.$t('message.addFail'));
                    }
                });
            },
            handleDeleteOilRecord: function(row, index) {
                row = deepClone(row);
                row.oilindex = Number(row.oilindex);
                var me = this;
                var url = myUrls.delOilRecord();
                utils.sendAjax(url, row, function(resp) {
                    if (resp.status == 0) {
                        me.oilTable.splice(index, 1);
                        me.cloneDataList.splice(index, 1);
                        me.$Message.success(vRoot.$t('message.deleteSucc'));
                    } else if (resp.status == 1) {
                        me.$Message.success(vRoot.$t('message.deleteOilRecordTip'));
                    } else {
                        me.$Message.error(vRoot.$t('message.deleteFail'));
                    }
                });
            },
            getTrackInfoContent: function(row, h, key) {

                var totoil = vRoot.$t('reportForm.totalOil');
                var speed = vRoot.$t('reportForm.speed');

                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');

                var srcad0 = vRoot.$t('reportForm.srcad0');
                var srcad1 = vRoot.$t('reportForm.srcad1');
                var srcad2 = vRoot.$t('reportForm.srcad2');
                var srcad3 = vRoot.$t('reportForm.srcad3');


                var status = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t('reportForm.reissue');

                var voltage = isZh ? "电压" : "Voltage";

                var content = [];
                var track = null;
                for (var i = 0; i < this.records.length; i++) {
                    var item = this.records[i];
                    if (row[key] == item.updatetime) {
                        track = item;
                        break;
                    }
                }

                if (track) {

                    content.push(h('p', {}, DateFormat.longToLocalDateTimeStr(track.updatetime)));
                    content.push(h('p', {}, speed + " : " + track.speed + "km/h"));
                    content.push(h('p', {}, totoil + " : " + track.totalad + "L"));
                    this.selectedLegend[usoil1] && content.push(h('p', {}, usoil1 + " : " + track.ad0 + "L"));
                    this.selectedLegend[usoil2] && content.push(h('p', {}, usoil2 + " : " + track.ad1 + "L"));
                    this.selectedLegend[usoil3] && content.push(h('p', {}, usoil3 + " : " + track.ad2 + "L"));
                    this.selectedLegend[usoil4] && content.push(h('p', {}, usoil4 + " : " + track.ad3 + "L"));
                    this.selectedLegend[srcad0] && content.push(h('p', {}, srcad0 + " : " + track.srcad0 + "L"));
                    this.selectedLegend[srcad1] && content.push(h('p', {}, srcad1 + " : " + track.srcad1 + "L"));
                    this.selectedLegend[srcad2] && content.push(h('p', {}, srcad2 + " : " + track.srcad2 + "L"));
                    this.selectedLegend[srcad3] && content.push(h('p', {}, srcad3 + " : " + track.srcad3 + "L"));
                    content.push(h('p', {}, status + " : " + (isZh ? track.strstatus : track.strstatusen)));
                    content.push(h('p', {}, reissue + " : " + (isZh ? (track.reissue == 0 ? '否' : '是') : (track.reissue == 0 ? 'No' : 'Yes'))));
                    this.selectedLegend[voltage] && content.push(h('p', {}, voltage + " : " + track.voltage + "V"));

                }



                return content;
            },
            initOilColumns: function() {
                var self = this;
                self.oilColumns.forEach(function(item) {
                    if (item.handle) {

                        item.render = function(h, param) {
                            var currentRow = self.cloneDataList[param.index];
                            var children = [];
                            item.handle.forEach(function(item) {

                                if (item === 'edit') {
                                    children.push(editButton(self, h, currentRow, param.index));
                                } else if (item === 'delete') {
                                    children.push(deleteButton(self, h, currentRow, param.index));
                                } else if (item === 'map') {
                                    children.push(mapButton(self, h, currentRow, param.index));
                                }

                            });

                            return h('div', children);
                        };
                    }

                    if (item.editable) {
                        item.render = function(h, params) {
                            var currentRow = self.cloneDataList[params.index];
                            // 非编辑状态
                            if (!currentRow.editting) {
                                // 日期类型单独 渲染(利用工具暴力的formatDate格式化日期)
                                if (item.date) {

                                    var contentChildren = self.getTrackInfoContent(currentRow, h, item.key);
                                    return h('Poptip', {
                                        props: {
                                            // width: 240,
                                            // height: 60,
                                            // content: content
                                            // popperClass: 'poptip-popper-class',
                                            placement: "bottom"
                                        },
                                    }, [
                                        h('Button', {
                                            props: {
                                                type: 'info',
                                                size: 'small'
                                            },
                                        }, DateFormat.longToLocalDateTimeStr(Number(currentRow[item.key]))),
                                        h(
                                            'div', {
                                                slot: 'content',
                                                attrs: {
                                                    slot: "content"
                                                }
                                            }, contentChildren
                                        )
                                    ]);
                                }
                                // 下拉类型中value与label不一致时单独渲染
                                if (item.option && Array.isArray(item.option)) {
                                    // 我这里为了简单的判断了第一个元素为object的情况,其实最好用every来判断所有元素
                                    if (typeof item.option[0] === 'object') {

                                        return h('span', item.option.find(findObjectInOption(currentRow[item.key])).label);
                                    }
                                }


                                return h('span', currentRow[item.key]);


                            } else {
                                if (item.option && Array.isArray(item.option)) {

                                    return h('div', {
                                        style: {

                                            // width: '100%',
                                            // height: '100%',
                                            // position: 'absolute',
                                            // let: '50%',
                                            // top: '50%',
                                            // 'marginTop': '-16px',
                                            // 'marginLeft': '-50px',
                                        }
                                    }, [
                                        h('Select', {
                                            props: {
                                                // ***重点***: 这里要写currentRow[params.column.key],绑定的是cloneDataList里的数据
                                                value: currentRow[params.column.key]
                                            },
                                            on: {
                                                'on-change': function(value) {
                                                    self.$set(currentRow, params.column.key, value)
                                                }
                                            }
                                        }, item.option.map(function(item) {
                                            return h('Option', {
                                                props: {
                                                    value: item.value || item,
                                                    label: item.label || item
                                                }
                                            }, item.label || item);
                                        }))
                                    ]);
                                } else if (item.date) {

                                    //如果含有date属性
                                    // return h('div', {}, DateFormat.format(new Date(currentRow[params.column.key]), 'yyyy-MM-dd hh:mm:ss'));
                                    return h('DatePicker', {
                                        props: {
                                            type: item.date.split('_')[0] || 'date',
                                            clearable: false,
                                            value: new Date(currentRow[params.column.key])
                                        },
                                        on: {
                                            'on-change': function(value) {
                                                self.$set(currentRow, params.column.key, value)
                                            }
                                        }
                                    });


                                } else {


                                    return h('Input', {
                                        props: {
                                            // type类型也是自定的属性
                                            type: item.input || 'text',
                                            // rows只有在input 为textarea时才会起作用
                                            rows: 3,
                                            value: currentRow[params.column.key]
                                        },
                                        on: {
                                            'on-change': function(event) {
                                                self.$set(currentRow, params.column.key, event.target.value)
                                            }
                                        }
                                    });

                                    // 默认input

                                }
                            }
                        }

                    }

                    if (item.key == 'oilVolume') {
                        item.render = function(h, params) {
                            var currentRow = self.cloneDataList[params.index];
                            return h('div', {}, Math.abs(currentRow.eoil - currentRow.soil).toFixed(2));
                            // return h('div', {}, currentRow[params.column.key])
                        }
                    }

                });
            },
            saveData: function(currentRow, index) {

                var self = this;
                // 修改当前的原始数据, 就不需要再从服务端获取了
                this.$set(this.oilTable, index, this.handleBackdata(currentRow))
                    // 需要保存的数据
                    // 模拟ajax
                    // setTimeout(function() {
                    //     // 重置编辑与保存状态
                    //     currentRow.saving = false;
                    //     currentRow.editting = false;
                    //     self.$Message.success('保存完成');

                // }, 1000)

                var url = myUrls.editOilRecordAll();
                var data = deepClone(currentRow);
                data.oilindex = Number(data.oilindex);
                data.oilstate = Number(data.oilstate);
                data.soil = data.soil * 100;
                data.eoil = data.eoil * 100;
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        currentRow.saving = false;
                        currentRow.editting = false;
                        self.$Message.success(vRoot.$t('message.changeSucc'));
                    } else if (resp.status == 1) {
                        self.$Message.error(vRoot.$t('message.deleteOilRecordTip'));
                    } else if (resp.status == 2) {
                        self.$Message.error(vRoot.$t('message.deleteOilRecordTip2'));
                    } else {
                        self.$Message.error(vRoot.$t('message.clearFail'));
                    }
                });

            },
            // 还原数据,用来与原始数据作对比的
            handleBackdata: function(object) {
                var clonedData = JSON.parse(JSON.stringify(object));
                delete clonedData.editting;
                delete clonedData.saving;
                return clonedData;
            },
            addStartOilTime: function() {
                if (editObject) {
                    editObject.soil = Number(this.oilCount);
                    editObject.begintime = this.dateCharts;
                    // this.$set(editObject, 'oilVolume', Math.abs(editObject.eoil - editObject.soil).toFixed(2))
                    editObject.oilVolume = Math.abs(editObject.eoil - editObject.soil).toFixed(2);
                } else {
                    this.$Message.error("请点击选择要编辑的记录");
                }
            },
            addEndOilTime: function() {
                if (editObject) {
                    editObject.eoil = Number(this.oilCount);
                    editObject.endtime = this.dateCharts;
                    editObject.oilVolume = Math.abs(editObject.eoil - editObject.soil).toFixed(2);
                    // this.$set(editObject, 'oilVolume', Math.abs(editObject.eoil - editObject.soil).toFixed(2))
                } else {
                    this.$Message.error("请点击选择要编辑的记录");
                }
            },
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.myChart = null;
            this.records = [];
            this.disMin = 0;
            if (reportTimeFrame) {
                this.dateVal = reportTimeFrame;
            }
            this.initMap();
            this.initOilColumns();

            var notRunTotalad = vRoot.$t('reportForm.notRunTotalad');

            var usoil1 = vRoot.$t('reportForm.oil1');
            var usoil2 = vRoot.$t('reportForm.oil2');
            var usoil3 = vRoot.$t('reportForm.oil3');
            var usoil4 = vRoot.$t('reportForm.oil4');

            var srcad0 = vRoot.$t('reportForm.srcad0');
            var srcad1 = vRoot.$t('reportForm.srcad1');
            var srcad2 = vRoot.$t('reportForm.srcad2');
            var srcad3 = vRoot.$t('reportForm.srcad3');

            var altitude = vRoot.$t('reportForm.altitude');
            var voltage = vRoot.$t('reportForm.voltage');



            if (isZh) {
                this.selectedLegend = {
                    "油液1": false,
                    "油液2": false,
                    "油液3": false,
                    "油液4": false,
                    "模拟量1": false,
                    "模拟量2": false,
                    "模拟量3": false,
                    "模拟量4": false,
                    "海拔": false,
                    "电压": false,
                }
            } else {
                this.selectedLegend = {
                    "Box1": false,
                    "Box2": false,
                    "Box3": false,
                    "Box4": false,
                    "srcad0": false,
                    "srcad1": false,
                    "srcad2": false,
                    "srcad3": false,
                    "Altitude": false,
                    "Voltage": false,
                }
            }
            // this.selectedLegend = {
            //     [usoil1]: false,
            //     [usoil2]: false,
            //     [usoil3]: false,
            //     [usoil4]: false,
            //     [srcad0]: false,
            //     [srcad1]: false,
            //     [srcad2]: false,
            //     [srcad3]: false,
            // }


            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.charts();

            this.chartsIns.getZr().on('click', function(params) {
                var pointInPixel = [params.offsetX, params.offsetY];
                if (me.chartsIns.containPixel('grid', pointInPixel)) {
                    var tracks = me.records;
                    if (tracks.length) {


                        var xIndex = me.chartsIns.convertFromPixel({
                            seriesIndex: 0
                        }, [params.offsetX, params.offsetY])[0];

                        me.oilCount = me.totalad[xIndex];
                        me.dateCharts = me.recvtime[xIndex];

                        var currentIndex = Math.ceil((tracks.length - xIndex) / 20);
                        var rowIndex = (tracks.length - xIndex) % 20;
                        if (rowIndex == 0) {
                            rowIndex = 19;
                        } else {
                            rowIndex = rowIndex - 1;
                        }
                        me.changePage(currentIndex);
                        me.currentIndex = currentIndex;

                        setTimeout(function() {
                            me.$refs.trackTable.$refs.tbody.clickCurrentRow(rowIndex);
                            var rowHeight = $('#oil-track tr.ivu-table-row')[0].getBoundingClientRect().height
                            $('div.ivu-table-body').animate({
                                scrollTop: (rowIndex * rowHeight) + 'px'
                            }, 300);
                        }, 500)
                    }
                }
            });





            this.chartsIns.on('legendselectchanged', function(param) {

                var columns = [
                    { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                    { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 160 },
                    { title: vRoot.$t('reportForm.updateTime'), key: 'updatetimeStr', sortable: true, width: 160 },
                    { title: vRoot.$t('reportForm.arrivedtimeStr'), key: 'arrivedtimeStr', sortable: true, width: 160 },
                    { title: vRoot.$t('reportForm.totalMileage') + '(km)', key: 'totaldistance', width: 110 },
                    { title: vRoot.$t('reportForm.totalOil'), key: 'totalad', width: 100 },
                ];

                var selected = param.selected;
                me.selectedLegend[notRunTotalad] = !!selected[notRunTotalad];
                me.selectedLegend[usoil1] = !!selected[usoil1];
                me.selectedLegend[usoil2] = !!selected[usoil2];
                me.selectedLegend[usoil3] = !!selected[usoil3];
                me.selectedLegend[usoil4] = !!selected[usoil4];
                me.selectedLegend[srcad0] = !!selected[srcad0];
                me.selectedLegend[srcad1] = !!selected[srcad1];
                me.selectedLegend[srcad2] = !!selected[srcad2];
                me.selectedLegend[srcad3] = !!selected[srcad3];
                me.selectedLegend[voltage] = selected[voltage];


                if (selected[notRunTotalad]) {
                    columns.push({ title: vRoot.$t('reportForm.notRunTotalad'), key: 'totalnotrunningad', width: 100 })
                }
                if (selected[usoil1]) {
                    columns.push({ title: vRoot.$t('reportForm.oil1'), key: 'ad0', width: 90 })
                }
                if (selected[usoil2]) {
                    columns.push({ title: vRoot.$t('reportForm.oil2'), key: 'ad1', width: 90 })
                }
                if (selected[usoil3]) {
                    columns.push({ title: vRoot.$t('reportForm.oil3'), key: 'ad2', width: 90 })
                }
                if (selected[usoil4]) {
                    columns.push({ title: vRoot.$t('reportForm.oil4'), key: 'ad3', width: 90 })
                }
                if (selected[srcad0]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad0'), key: 'srcad0', width: 90 })
                }
                if (selected[srcad1]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad1'), key: 'srcad1', width: 90 })
                }
                if (selected[srcad2]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad2'), key: 'srcad2', width: 90 })
                }
                if (selected[srcad3]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad3'), key: 'srcad3', width: 90 })
                }
                if (selected[altitude]) {
                    columns.push({ title: vRoot.$t('reportForm.altitude') + (isZh ? "(米)" : "(M)"), key: 'altitude', width: 90 })
                }
                if (selected[voltage]) {
                    columns.push({ title: vRoot.$t('reportForm.voltage') + '(V)', key: 'voltage', width: 90 })
                }


                // me.initOilColumns();

                me.columns = columns.concat([
                    { title: vRoot.$t('reportForm.speed'), key: 'speed', width: 80 },
                    { title: vRoot.$t('reportForm.reissue'), key: 'reissue', width: 80 },
                    { title: vRoot.$t('reportForm.status'), key: 'strstatus', width: 160, },
                    {
                        title: vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                        width: 210,
                        render: function(h, params) {
                            var row = params.row;
                            var callat = row.callat.toFixed(5);
                            var callon = row.callon.toFixed(5);

                            if (callat && callon) {
                                if (row.address == null) {

                                    return h('Button', {
                                        props: {
                                            type: 'error',
                                            size: 'small'
                                        },
                                        on: {
                                            click: function() {
                                                utils.getJiuHuAddressSyn(callon, callat, function(resp) {
                                                    if (resp && resp.address) {
                                                        vueInstanse.records[params.index].address = resp.address;
                                                        LocalCacheMgr.setAddress(callon, callat, resp.address);
                                                    }
                                                })
                                            }
                                        }
                                    }, callon + "," + callat)

                                } else {
                                    return h('Tooltip', {
                                        props: {
                                            content: row.address,
                                            placement: "top-start",
                                            maxWidth: 200
                                        },
                                    }, [
                                        h('Button', {
                                            props: {
                                                type: 'primary',
                                                size: 'small'
                                            }
                                        }, callon + "," + callat)
                                    ]);
                                }
                            } else {
                                return h('span', {}, '');
                            }
                        },
                    },
                ]);
            });
        }
    });
}

function mileageOilConsumption(groupslist) {
    vueInstanse = new Vue({
        el: "#mileage-oil-consumption",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            groupslist: [],
            isShowCard: false,
            contentString: "",
            metre: '1000',
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 160 },
                { title: vRoot.$t('reportForm.updateTime'), key: 'updatetimeStr', sortable: true, width: 160 },
                { title: vRoot.$t('reportForm.arrivedtimeStr'), key: 'arrivedtimeStr', sortable: true, width: 160 },
                { title: vRoot.$t('reportForm.totalMileage') + '(km)', key: 'totaldistance', width: 110 },
                { title: vRoot.$t('reportForm.totalOil'), key: 'totalad', width: 100 },
                { title: vRoot.$t('reportForm.notRunTotalad'), key: 'totalnotrunningad', width: 100 },
                { title: vRoot.$t('reportForm.speed'), key: 'speed', width: 110 },
                { title: vRoot.$t('reportForm.reissue'), key: 'reissue', width: 120 },
                { title: vRoot.$t('reportForm.status'), key: 'strstatus', width: 300 },
                {
                    title: vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                    width: 210,
                    render: function(h, params) {
                        var row = params.row;
                        var callat = row.callat.toFixed(5);
                        var callon = row.callon.toFixed(5);

                        if (callat && callon) {
                            if (row.address == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(callon, callat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.records[params.index].address = resp.address;
                                                    LocalCacheMgr.setAddress(callon, callat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, callon + "," + callat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.address,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, callon + "," + callat)
                                ]);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
            ],
            tableData: [],
            recvtime: [],
            totalad: [],
            veo: [],
            distance: [],
            oil1: [],
            oil2: [],
            oil3: [],
            oil4: [],
            srcad0: [],
            srcad1: [],
            srcad2: [],
            srcad3: [],
            altitudes: [],
            voltages: [],
            devReissue: [],
            currentIndex: 1,

            oilColumns: [{
                    // title: isZh ? '编号' : 'index',
                    type: 'index',
                    width: 70
                },
                {
                    title: isZh ? '油路' : 'Box Idex',
                    key: 'oilindex',
                    option: oilIndexLabel,
                    width: 120,
                    editable: true
                }, {
                    width: 100,
                    key: 'oilstate',
                    title: (isZh ? '状态' : 'Status'),
                    option: [{ label: isZh ? '加油' : 'Refuel', value: '1' }, { label: isZh ? '漏油' : 'Leak', value: '-1' }],
                    editable: true
                }, {
                    title: (isZh ? '油量' : 'Fuel Volume') + '(L)',
                    key: 'oilVolume',
                    width: 100,
                    render: function(h, params) {
                        var row = params.row;
                        return h('span', Math.abs(row.eoil - row.soil).toFixed(2));
                    }
                }, {
                    title: (isZh ? '开始油量' : 'Start Fuel Volume') + '(L)',
                    width: 110,
                    key: 'soil',
                    input: 'number',
                    editable: true,
                }, {
                    title: (isZh ? '结束油量' : 'End Fuel Volume') + '(L)',
                    key: 'eoil',
                    input: 'number',
                    width: 110,
                    editable: true,
                }, {
                    title: isZh ? '开始时间' : 'Begin Time',
                    key: 'begintime',
                    date: 'datetime_yyyy-MM-dd hh:mm:ss',
                    width: 165,
                    editable: true,
                }, {
                    title: isZh ? '结束时间' : 'End Time',
                    key: 'endtime',
                    date: 'datetime_yyyy-MM-dd hh:mm:ss',
                    width: 165,
                    editable: true,
                }, {
                    title: isZh ? '备注' : 'Marker',
                    width: 185,
                    key: 'marker',
                    input: 'text',
                    editable: true,
                }, {
                    title: isZh ? '操作' : 'action',
                    width: 185,
                    key: 'handle',
                    handle: ['edit', 'delete', 'map'],
                    render: function(h) {}
                },
                {
                    title: vRoot.$t('reportForm.saddress'),
                    width: 300,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.slat ? row.slat.toFixed(5) : null;
                        var lon = row.slon ? row.slon.toFixed(5) : null;
                        if (lat && lon) {
                            if (row.saddress == null) {
                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    row.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('span', {}, row.saddress);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
                { title: isZh ? '距离(米)' : 'Distance(m)', key: 'distance', width: 100 },
                { title: isZh ? '平均速度(km/h)' : 'Average speed (km / h)', key: 'avgspeed', width: 140 },
                { title: isZh ? '时长(小时)' : 'Duration(Hour)', key: 'durationStr', width: 110 },
                { title: isZh ? '阈值(L)' : 'Threshold', key: 'threshold', width: 100 },

            ],
            oilTable: [],
            cloneDataList: [],
            trackDetailModal: false,
            tabActive: 'oil'
        },
        mixins: [reportMixin],
        methods: {
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('oil-details-map');
            },
            queryTracks: function(row) {
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: DateFormat.longToLocalDateTimeStr(row.begintime),
                        endtime: DateFormat.longToLocalDateTimeStr(row.endtime),
                        interval: 5,
                        timezone: timeDifference,
                    };
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.trackDetailModal = true;
                            utils.markersAndLineLayerToMap(me, records);
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            exportData: function() {
                if (this.tabActive == 'oil') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            isZh ? '油路' : 'Box Index',
                            (isZh ? '状态' : 'Status'),
                            (isZh ? '油量' : 'Fuel Volume') + '(L)',
                            (isZh ? '开始油量' : 'Start Fuel Volume') + '(L)',
                            (isZh ? '结束油量' : 'End Fuel Volume') + '(L)',
                            isZh ? '开始时间' : 'Begin Time',
                            isZh ? '结束时间' : 'End Time',
                            isZh ? '备注' : 'Marker',
                            vRoot.$t('reportForm.saddress'),
                            isZh ? '距离(米)' : 'Distance(m)',
                            isZh ? '平均速度(km/h)' : 'Average speed (km / h)',
                            isZh ? '时长' : 'Duration',
                            isZh ? '阈值(L)' : 'Threshold',

                        ]
                    ];

                    function findOilIndexStr(oilindex) {
                        var str = '';
                        oilIndexLabel.forEach(function(item) {
                            if (item.value == oilindex) {
                                str = item.label;
                            }
                        })
                        return str;
                    }
                    this.oilTable.forEach(function(item, index) {

                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(findOilIndexStr(item.oilindex));
                        itemArr.push(item.oilstate == 1 ? (isZh ? '加油' : 'Fuel') : (isZh ? '漏油' : 'Oil leak'));
                        itemArr.push(Math.abs(item.eoil - item.soil).toFixed(2));
                        itemArr.push(item.soil);
                        itemArr.push(item.eoil);
                        itemArr.push(DateFormat.longToLocalDateTimeStr(item.begintime));
                        itemArr.push(DateFormat.longToLocalDateTimeStr(item.endtime));
                        itemArr.push(item.marker ? item.marker : '');
                        itemArr.push(item.saddress);
                        itemArr.push(item.distance);
                        itemArr.push(item.avgspeed);
                        itemArr.push(item.durationStr);
                        itemArr.push(item.threshold);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.addOrLeakOilList') + '-' + this.queryDeviceId,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                } else {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t('reportForm.updateTime'),
                            vRoot.$t('reportForm.arrivedtimeStr'),
                            vRoot.$t('reportForm.totalMileage') + '(km)',
                            vRoot.$t('reportForm.totalOil'),
                            vRoot.$t('reportForm.notRunTotalad'),
                            vRoot.$t('reportForm.speed'),
                            vRoot.$t('reportForm.reissue'),
                            vRoot.$t('reportForm.status'),
                            vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                        ]
                    ];

                    this.records.forEach(function(item, index) {
                        var itemArr = [];
                        var callat = item.callat.toFixed(5);
                        var callon = item.callon.toFixed(5);
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.updatetimeStr);
                        itemArr.push(item.arrivedtimeStr);
                        itemArr.push(item.totaldistance);
                        itemArr.push(item.totalad);
                        itemArr.push(item.totalnotrunningad);
                        itemArr.push(item.speed);
                        itemArr.push(item.reissue);
                        itemArr.push(item.strstatus);
                        itemArr.push(callon + ',' + callat);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t("reportForm.mileageOilConsumption") + '-' + this.queryDeviceId,
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();
                }
            },
            queryAddOilStatus: function(tracks) {
                if (tracks) {
                    tracks.forEach(function(tracks, index) {
                        tracks.index = index;
                    });

                    var me = this;
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        devices: [this.queryDeviceId],
                        oilstate: 99,
                        oilindex: 0
                    };
                    utils.sendAjax(myUrls.reportOilRecord(), data, function(resp) {
                        self.loading = false;
                        if (resp.status == 0) {
                            if (resp.records) {
                                var oilArr = [];
                                var increaseOil = 0;
                                var reduceOil = 0;
                                resp.records.forEach(function(item) {
                                    var index = 1;
                                    item.records.forEach(function(record) {
                                        var oilstate = record.oilstate;
                                        if (oilstate == -1 || oilstate == 1) {


                                            var slat = record.slat.toFixed(5);
                                            var slon = record.slon.toFixed(5);
                                            var saddress = LocalCacheMgr.getAddress(slon, slat);
                                            if (saddress != null) {
                                                record.saddress = saddress;
                                            } else {
                                                record.saddress = null;
                                            };

                                            record.eoil = record.eoil / 100;
                                            record.soil = record.soil / 100;
                                            record.oilstate = String(oilstate);
                                            record.oilindex = String(record.oilindex);
                                            record.editting = false;
                                            record.saving = false;
                                            record.durationStr = (record.duration / 1000 / 3600).toFixed(2);;

                                            oilArr.push(record);
                                            index++;
                                        }
                                    });
                                });

                                me.oilTable = oilArr;
                                me.cloneDataList = deepClone(oilArr);

                                // var markPoints = utils.calMarkPoint(tracks, resp.records);
                                me.markPointData = utils.calMarkPoint(tracks, resp.records[0].records, 0);
                                me.markPointDataOil1 = utils.calMarkPoint(tracks, resp.records[0].records, 1);
                                me.markPointDataOil2 = utils.calMarkPoint(tracks, resp.records[0].records, 2);
                                me.markPointDataOil3 = utils.calMarkPoint(tracks, resp.records[0].records, 3);
                                me.markPointDataOil4 = utils.calMarkPoint(tracks, resp.records[0].records, 4);
                                me.markPointDataOil99 = utils.calMarkPoint(tracks, resp.records[0].records, 99);

                                me.charts();

                            } else {
                                me.$Message.error(self.$t("reportForm.noRecord"));
                            }
                        } else {
                            me.$Message.error(resp.cause);
                        }
                    })
                };

            },
            onRowClick: function(row) {
                var me = this;
                this.isShowCard = true;
                this.queryTrackDetail(row, function(resp) {
                    if (resp.track) {
                        me.contentString = JSON.stringify(resp.track);
                    } else {
                        vm.$Message.error(me.$t("reportForm.noRecord"));
                    }
                });
            },
            queryTrackDetail: function(row, callback) {
                var data = {
                    deviceid: this.queryDeviceId,
                    updatetime: row.updatetime,
                    trackid: row.trackid
                }
                var url = myUrls.queryTrackDetail();
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        callback(resp);
                    }
                })
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentPageIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            charts: function() {
                var totoil = vRoot.$t('reportForm.totalOil');
                var notRunTotalad = vRoot.$t('reportForm.notRunTotalad');
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');

                var srcad0 = vRoot.$t('reportForm.srcad0');
                var srcad1 = vRoot.$t('reportForm.srcad1');
                var srcad2 = vRoot.$t('reportForm.srcad2');
                var srcad3 = vRoot.$t('reportForm.srcad3');

                var cotgasus = vRoot.$t('reportForm.oil');
                var status = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t('reportForm.reissue');

                var altitude = vRoot.$t('reportForm.altitude');
                var voltage = vRoot.$t('reportForm.voltage');

                var option = {
                    title: {
                        // text: time + '/' + cotgasus,
                        // x: 'center',
                        // textStyle: {
                        //     fontSize: 12,
                        //     fontWeight: 'bolder',
                        //     color: '#333'
                        // }
                    },
                    grid: {
                        top: 30,
                        left: 60,
                        right: 60,
                        bottom: 40,
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            // console.log(v);
                            var data = time + ' : ' + v[0].value + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName && v[i].seriesName != time) {
                                    if (v[i].seriesName == dis) {
                                        var currentDistance = v[i].value;
                                        var totalDistance = ((Number(currentDistance) + firstDistance / 1000)).toFixed(2);
                                        data += v[i].seriesName + ' : ' + currentDistance + "km(T:" + totalDistance + 'km)<br/>';
                                    } else if (v[i].seriesName == notRunTotalad || v[i].seriesName == totoil || v[i].seriesName == usoil1 || v[i].seriesName == usoil2 || v[i].seriesName == usoil3 || v[i].seriesName == usoil4) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'L<br/>';
                                    } else if (v[i].seriesName == speed) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else if (v[i].seriesName == altitude) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'm<br/>';
                                    } else if (v[i].seriesName == voltage) {
                                        data += v[i].seriesName + ' : ' + v[i].value + 'V<br/>';
                                    } else {
                                        data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, totoil, notRunTotalad, usoil1, usoil2, usoil3, usoil4, srcad0, srcad1, srcad2, srcad3, altitude, voltage],
                        selected: this.selectedLegend,
                        x: 'left',
                        // width: 600,
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        //fillerColor:'rgb(244,129,38,0.8)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.distance
                    }],
                    yAxis: [{
                        name: '', //totoil + '/' + speed
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: '', //dis
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.veo
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distance
                        }, {
                            smooth: true,
                            name: totoil,
                            type: 'line',
                            symbol: 'none',
                            color: '#C1232B',
                            data: this.totalad,
                            markPoint: {
                                data: this.markPointData,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: notRunTotalad,
                            type: 'line',
                            symbol: 'none',
                            color: '#E2242B',
                            data: this.notRunTotalad,
                            markPoint: {
                                data: this.markPointDataOil99,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil1,
                            type: 'line',
                            symbol: 'none',
                            color: '#8E388E',
                            data: this.oil1,
                            markPoint: {
                                data: this.markPointDataOil1,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },

                        {
                            smooth: true,
                            name: usoil2,
                            type: 'line',
                            symbol: 'none',
                            color: '#FF4500',
                            data: this.oil2,
                            markPoint: {
                                data: this.markPointDataOil2,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil3,
                            type: 'line',
                            symbol: 'none',
                            color: '#2177C7',
                            data: this.oil3,
                            markPoint: {
                                data: this.markPointDataOil3,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: usoil4,
                            type: 'line',
                            symbol: 'none',
                            color: '#B05432',
                            data: this.oil4,
                            markPoint: {
                                data: this.markPointDataOil4,
                                symbolSize: 36,
                                symbolKeepAspect: true,
                            }
                        },
                        {
                            smooth: true,
                            name: srcad0,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad0
                        },
                        {
                            smooth: true,
                            name: srcad1,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad1
                        },
                        {
                            smooth: true,
                            name: srcad2,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad2
                        },
                        {
                            smooth: true,
                            name: srcad3,
                            type: 'line',
                            symbol: 'none',
                            color: '#000000',
                            data: this.srcad3
                        },
                        {
                            smooth: true,
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates
                        },
                        {
                            smooth: true,
                            name: reissue,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devReissue
                        },
                        {
                            smooth: true,
                            name: altitude,
                            type: 'line',
                            symbol: 'none',
                            color: '#245779',
                            data: this.altitudes
                        },
                        {
                            smooth: true,
                            name: voltage,
                            type: 'line',
                            symbol: 'none',
                            color: '#8CDCDA',
                            data: this.voltages
                        },
                    ]
                };



                this.chartsIns.setOption(option, true);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 400;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") { return };
                var self = this;
                if (this.isSelectAll === null) {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                    return;
                };
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                    intervalm: Number(this.metre)
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportOilMileage(), data, function(resp) {
                    self.loading = false;
                    self.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                    self.markPointData = [];
                    if (resp.status == 0) {
                        if (resp.records) {
                            var records = [],
                                totalads = [],
                                notRunTotalad = [],
                                veo = [],
                                distance = [],
                                recvtime = [],
                                oil1 = [],
                                oil2 = [],
                                oil3 = [],
                                oil4 = [],
                                srcad0 = [],
                                srcad1 = [],
                                srcad2 = [],
                                srcad3 = [],
                                devReissue = [],
                                markPointData = [],
                                altitudes = [],
                                voltages = [],
                                devStates = [];
                            firstDistance = 0;

                            resp.records.forEach(function(item, index) {
                                // var independent = item.independent === 0;
                                if (item.records) {
                                    records = item.records;
                                    records.forEach(function(record, index) {
                                        if (index == 0) {
                                            firstDistance = record.totaldistance;
                                        };
                                        var callon = record.callon.toFixed(5);
                                        var callat = record.callat.toFixed(5);
                                        var address = LocalCacheMgr.getAddress(callon, callat);
                                        if (address != null) {
                                            record.address = address;
                                        } else {
                                            record.address = null;
                                        }
                                        var totalad = record.totalad;
                                        var totalnotrunningad = record.totalnotrunningad;
                                        var ad0 = record.ad0;
                                        var ad1 = record.ad1;
                                        var ad2 = record.ad2;
                                        var ad3 = record.ad3;
                                        if (ad0 < 0) {
                                            ad0 = 0;
                                        };
                                        if (ad1 < 0) {
                                            ad1 = 0;
                                        };
                                        if (ad2 < 0) {
                                            ad2 = 0;
                                        };
                                        if (ad3 < 0) {
                                            ad3 = 0;
                                        };
                                        record.totalad = totalad / 100;
                                        record.totalnotrunningad = totalnotrunningad / 100;
                                        record.ad0 = ad0 / 100;
                                        record.ad1 = ad1 / 100;
                                        record.ad2 = ad2 / 100;
                                        record.ad3 = ad3 / 100;
                                        record.speed = (record.speed / 1000).toFixed(2);
                                        record.voltage = record.voltage / 100.0;
                                        record.updatetimeStr = DateFormat.longToLocalDateTimeStr(record.updatetime);
                                        record.arrivedtimeStr = DateFormat.longToLocalDateTimeStr(record.arrivedtime);
                                        record.devicename = vstore.state.deviceInfos[self.queryDeviceId].devicename;
                                        totalads.push(record.totalad);
                                        notRunTotalad.push(record.totalnotrunningad);
                                        veo.push(record.speed);
                                        record.totaldistance = ((record.totaldistance - firstDistance) / 1000).toFixed(2);
                                        distance.push(record.totaldistance);
                                        recvtime.push(record.updatetimeStr);
                                        oil1.push(record.ad0);
                                        oil2.push(record.ad1);
                                        oil3.push(record.ad2);
                                        oil4.push(record.ad3);
                                        srcad0.push(record.srcad0);
                                        srcad1.push(record.srcad1);
                                        srcad2.push(record.srcad2);
                                        srcad3.push(record.srcad3);
                                        if (!isZh) {
                                            record.strstatus = record.strstatusen;
                                        }
                                        devStates.push(record.strstatus);
                                        devReissue.push(record.reissue == 0 ? self.$t('header.no') : self.$t('header.yes'));

                                        altitudes.push(record.altitude);
                                        voltages.push(record.voltage);
                                    });
                                }

                            });


                            // self.markPointData = markPointData;
                            self.totalad = totalads;
                            self.notRunTotalad = notRunTotalad;
                            self.veo = veo;
                            self.distance = distance;
                            self.recvtime = recvtime;
                            self.oil1 = oil1;
                            self.oil2 = oil2;
                            self.oil3 = oil3;
                            self.oil4 = oil4;
                            self.srcad0 = srcad0;
                            self.srcad1 = srcad1;
                            self.srcad2 = srcad2;
                            self.srcad3 = srcad3;
                            self.records = records;
                            self.devStates = devStates;
                            self.devReissue = devReissue;
                            self.altitudes = altitudes;
                            self.voltages = voltages;

                            self.queryAddOilStatus(deepClone(records));

                            self.total = records.length;
                            records.sort(function(a, b) {
                                return b.updatetime - a.updatetime;
                            })
                            records.forEach(function(item, index) {
                                item.index = index + 1;
                            })
                            self.currentPageIndex = 1;
                            self.tableData = records.slice(0, 20);



                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                }, function() {
                    self.loading = false;
                })


            },
            addOilRecord: function() {
                var me = this;
                var url = myUrls.addOilRecord();
                var data = {
                    deviceid: this.queryDeviceId,
                    begintime: DateFormat.dateTimeStrToLong(this.dateVal[0] + ' 00:00:00', 0),
                    endtime: DateFormat.dateTimeStrToLong(this.dateVal[1] + ' 23:59:59', 0) //结束时间' ,
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        var oilRecord = resp.oilRecord;
                        oilRecord.oilindex = String(oilRecord.oilindex);
                        oilRecord.oilstate = String(oilRecord.oilstate);
                        oilRecord.saving = false;
                        oilRecord.editting = false;
                        me.cloneDataList.push(oilRecord);
                        me.oilTable.push(deepClone(oilRecord));
                        me.$Message.success(vRoot.$t('message.addSucc'));
                    } else {
                        me.$Message.error(vRoot.$t('message.addFail'));
                    }
                });
            },
            handleDeleteOilRecord: function(row, index) {
                row = deepClone(row);
                row.oilindex = Number(row.oilindex);
                var me = this;
                var url = myUrls.delOilRecord();
                utils.sendAjax(url, row, function(resp) {
                    if (resp.status == 0) {
                        me.oilTable.splice(index, 1);
                        me.cloneDataList.splice(index, 1);
                        me.$Message.success(vRoot.$t('message.deleteSucc'));
                    } else if (resp.status == 1) {
                        me.$Message.success(vRoot.$t('message.deleteOilRecordTip'));
                    } else {
                        me.$Message.error(vRoot.$t('message.deleteFail'));
                    }
                });
            },
            getTrackInfoContent: function(row, h, key) {

                var totoil = vRoot.$t('reportForm.totalOil');
                var speed = vRoot.$t('reportForm.speed');

                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');

                var srcad0 = vRoot.$t('reportForm.srcad0');
                var srcad1 = vRoot.$t('reportForm.srcad1');
                var srcad2 = vRoot.$t('reportForm.srcad2');
                var srcad3 = vRoot.$t('reportForm.srcad3');


                var status = vRoot.$t('reportForm.status');
                var reissue = vRoot.$t('reportForm.reissue');

                var voltage = isZh ? "电压" : "Voltage";

                var content = [];
                var track = null;
                for (var i = 0; i < this.records.length; i++) {
                    var item = this.records[i];
                    if (row[key] == item.updatetime) {
                        track = item;
                        break;
                    }
                }

                if (track) {

                    content.push(h('p', {}, DateFormat.longToLocalDateTimeStr(track.updatetime)));
                    content.push(h('p', {}, speed + " : " + track.speed + "km/h"));
                    content.push(h('p', {}, totoil + " : " + track.totalad + "L"));
                    this.selectedLegend[usoil1] && content.push(h('p', {}, usoil1 + " : " + track.ad0 + "L"));
                    this.selectedLegend[usoil2] && content.push(h('p', {}, usoil2 + " : " + track.ad1 + "L"));
                    this.selectedLegend[usoil3] && content.push(h('p', {}, usoil3 + " : " + track.ad2 + "L"));
                    this.selectedLegend[usoil4] && content.push(h('p', {}, usoil4 + " : " + track.ad3 + "L"));
                    this.selectedLegend[srcad0] && content.push(h('p', {}, srcad0 + " : " + track.srcad0 + "L"));
                    this.selectedLegend[srcad1] && content.push(h('p', {}, srcad1 + " : " + track.srcad1 + "L"));
                    this.selectedLegend[srcad2] && content.push(h('p', {}, srcad2 + " : " + track.srcad2 + "L"));
                    this.selectedLegend[srcad3] && content.push(h('p', {}, srcad3 + " : " + track.srcad3 + "L"));
                    content.push(h('p', {}, status + " : " + (isZh ? track.strstatus : track.strstatusen)));
                    content.push(h('p', {}, reissue + " : " + (isZh ? (track.reissue == 0 ? '否' : '是') : (track.reissue == 0 ? 'No' : 'Yes'))));
                    this.selectedLegend[voltage] && content.push(h('p', {}, voltage + " : " + track.voltage + "V"));

                }



                return content;
            },
            initOilColumns: function() {
                var self = this;
                self.oilColumns.forEach(function(item) {
                    if (item.handle) {

                        item.render = function(h, param) {
                            var currentRow = self.cloneDataList[param.index];
                            var children = [];
                            item.handle.forEach(function(item) {

                                if (item === 'edit') {
                                    children.push(editButton(self, h, currentRow, param.index));
                                } else if (item === 'delete') {
                                    children.push(deleteButton(self, h, currentRow, param.index));
                                } else if (item === 'map') {
                                    children.push(mapButton(self, h, currentRow, param.index));
                                }

                            });

                            return h('div', children);
                        };
                    }

                    if (item.editable) {
                        item.render = function(h, params) {
                            var currentRow = self.cloneDataList[params.index];
                            // 非编辑状态
                            if (!currentRow.editting) {
                                // 日期类型单独 渲染(利用工具暴力的formatDate格式化日期)
                                if (item.date) {

                                    var contentChildren = self.getTrackInfoContent(currentRow, h, item.key);
                                    return h('Poptip', {
                                        props: {
                                            // width: 240,
                                            // height: 60,
                                            // content: content
                                            // popperClass: 'poptip-popper-class',
                                            placement: "bottom"
                                        },
                                    }, [
                                        h('Button', {
                                            props: {
                                                type: 'info',
                                                size: 'small'
                                            },
                                        }, DateFormat.longToLocalDateTimeStr(Number(currentRow[item.key]))),
                                        h(
                                            'div', {
                                                slot: 'content',
                                                attrs: {
                                                    slot: "content"
                                                }
                                            }, contentChildren
                                        )
                                    ]);
                                }
                                // 下拉类型中value与label不一致时单独渲染
                                if (item.option && Array.isArray(item.option)) {
                                    // 我这里为了简单的判断了第一个元素为object的情况,其实最好用every来判断所有元素
                                    if (typeof item.option[0] === 'object') {

                                        return h('span', item.option.find(findObjectInOption(currentRow[item.key])).label);
                                    }
                                }


                                return h('span', currentRow[item.key]);


                            } else {
                                if (item.option && Array.isArray(item.option)) {


                                    return h('div', {
                                        style: {

                                            // width: '100%',
                                            // height: '100%',
                                            // position: 'absolute',
                                            // let: '50%',
                                            // top: '50%',
                                            // 'marginTop': '-16px',
                                            // 'marginLeft': '-50px',
                                        }
                                    }, [
                                        h('Select', {
                                            props: {
                                                // ***重点***: 这里要写currentRow[params.column.key],绑定的是cloneDataList里的数据
                                                value: currentRow[params.column.key]
                                            },
                                            on: {
                                                'on-change': function(value) {
                                                    self.$set(currentRow, params.column.key, value)
                                                }
                                            }
                                        }, item.option.map(function(item) {
                                            return h('Option', {
                                                props: {
                                                    value: item.value || item,
                                                    label: item.label || item
                                                }
                                            }, item.label || item);
                                        }))
                                    ]);
                                } else if (item.date) {

                                    //如果含有date属性
                                    return h('DatePicker', {
                                        props: {
                                            type: item.date.split('_')[0] || 'date',
                                            clearable: false,
                                            value: new Date(currentRow[params.column.key])
                                        },
                                        on: {
                                            'on-change': function(value) {
                                                self.$set(currentRow, params.column.key, value)
                                            }
                                        }
                                    });
                                } else {
                                    // 默认input
                                    return h('Input', {
                                        props: {
                                            // type类型也是自定的属性
                                            type: item.input || 'text',
                                            // rows只有在input 为textarea时才会起作用
                                            rows: 3,
                                            value: currentRow[params.column.key]
                                        },
                                        on: {
                                            'on-change': function(event) {
                                                self.$set(currentRow, params.column.key, event.target.value)
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                });
            },
            saveData: function(currentRow, index) {

                var self = this;
                // 修改当前的原始数据, 就不需要再从服务端获取了
                this.$set(this.oilTable, index, this.handleBackdata(currentRow))
                    // 需要保存的数据
                    // 模拟ajax
                    // setTimeout(function() {
                    //     // 重置编辑与保存状态
                    //     currentRow.saving = false;
                    //     currentRow.editting = false;
                    //     self.$Message.success('保存完成');

                // }, 1000)

                var url = myUrls.editOilRecordAll();
                var data = deepClone(currentRow);
                data.oilindex = Number(data.oilindex);
                data.oilstate = Number(data.oilstate);
                data.soil = data.soil * 100;
                data.eoil = data.eoil * 100;
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        currentRow.saving = false;
                        currentRow.editting = false;
                        self.$Message.success(vRoot.$t('message.changeSucc'));
                    } else if (resp.status == 1) {
                        self.$Message.success(vRoot.$t('message.deleteOilRecordTip'));
                    } else {
                        self.$Message.error(vRoot.$t('message.clearFail'));
                    }
                });

            },
            // 还原数据,用来与原始数据作对比的
            handleBackdata: function(object) {
                var clonedData = JSON.parse(JSON.stringify(object));
                delete clonedData.editting;
                delete clonedData.saving;
                return clonedData;
            }
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.myChart = null;
            this.records = [];
            this.disMin = 0;
            this.initMap();
            this.initOilColumns();

            var notRunTotalad = vRoot.$t('reportForm.notRunTotalad');
            var usoil1 = vRoot.$t('reportForm.oil1');
            var usoil2 = vRoot.$t('reportForm.oil2');
            var usoil3 = vRoot.$t('reportForm.oil3');
            var usoil4 = vRoot.$t('reportForm.oil4');

            var srcad0 = vRoot.$t('reportForm.srcad0');
            var srcad1 = vRoot.$t('reportForm.srcad1');
            var srcad2 = vRoot.$t('reportForm.srcad2');
            var srcad3 = vRoot.$t('reportForm.srcad3');

            var altitude = vRoot.$t('reportForm.altitude');
            var voltage = vRoot.$t('reportForm.voltage');



            if (isZh) {
                this.selectedLegend = {
                    "油液1": false,
                    "油液2": false,
                    "油液3": false,
                    "油液4": false,
                    "模拟量1": false,
                    "模拟量2": false,
                    "模拟量3": false,
                    "模拟量4": false,
                    "海拔": false,
                    "电压": false,
                }
            } else {
                this.selectedLegend = {
                    "Box1": false,
                    "Box2": false,
                    "Box3": false,
                    "Box4": false,
                    "srcad0": false,
                    "srcad1": false,
                    "srcad2": false,
                    "srcad3": false,
                    "Altitude": false,
                    "Voltage": false,
                }
            }
            // this.selectedLegend = {
            //     [usoil1]: false,
            //     [usoil2]: false,
            //     [usoil3]: false,
            //     [usoil4]: false,
            //     [srcad0]: false,
            //     [srcad1]: false,
            //     [srcad2]: false,
            //     [srcad3]: false,
            // }


            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.charts();

            this.chartsIns.getZr().on('click', function(params) {
                var pointInPixel = [params.offsetX, params.offsetY];
                if (me.chartsIns.containPixel('grid', pointInPixel)) {
                    var tracks = me.records;
                    if (tracks.length) {
                        var xIndex = me.chartsIns.convertFromPixel({
                            seriesIndex: 0
                        }, [params.offsetX, params.offsetY])[0];
                        var currentIndex = Math.ceil((tracks.length - xIndex) / 20);
                        var rowIndex = (tracks.length - xIndex) % 20;
                        if (rowIndex == 0) {
                            rowIndex = 19;
                        } else {
                            rowIndex = rowIndex - 1;
                        }
                        me.changePage(currentIndex);
                        me.currentIndex = currentIndex;

                        setTimeout(function() {
                            me.$refs.trackTable.$refs.tbody.clickCurrentRow(rowIndex);
                            var rowHeight = $('#oil-track tr.ivu-table-row')[0].getBoundingClientRect().height
                            $('div.ivu-table-body').animate({
                                scrollTop: (rowIndex * rowHeight) + 'px'
                            }, 300);
                        }, 500)
                    }
                }
            });





            this.chartsIns.on('legendselectchanged', function(param) {

                var columns = [
                    { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                    { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 160 },
                    { title: vRoot.$t('reportForm.updateTime'), key: 'updatetimeStr', sortable: true, width: 160 },
                    { title: vRoot.$t('reportForm.arrivedtimeStr'), key: 'arrivedtimeStr', sortable: true, width: 160 },
                    { title: vRoot.$t('reportForm.totalMileage') + '(km)', key: 'totaldistance', width: 110 },
                    { title: vRoot.$t('reportForm.totalOil'), key: 'totalad', width: 100 },
                ];

                var selected = param.selected;

                me.selectedLegend[usoil1] = !!selected[usoil1];
                me.selectedLegend[usoil2] = !!selected[usoil2];
                me.selectedLegend[usoil3] = !!selected[usoil3];
                me.selectedLegend[usoil4] = !!selected[usoil4];
                me.selectedLegend[srcad0] = !!selected[srcad0];
                me.selectedLegend[srcad1] = !!selected[srcad1];
                me.selectedLegend[srcad2] = !!selected[srcad2];
                me.selectedLegend[srcad3] = !!selected[srcad3];
                me.selectedLegend[voltage] = selected[voltage];

                if (selected[notRunTotalad]) {
                    columns.push({ title: vRoot.$t('reportForm.notRunTotalad'), key: 'totalnotrunningad', width: 100 })
                }
                if (selected[usoil1]) {
                    columns.push({ title: vRoot.$t('reportForm.oil1'), key: 'ad0', width: 90 })
                }
                if (selected[usoil2]) {
                    columns.push({ title: vRoot.$t('reportForm.oil2'), key: 'ad1', width: 90 })
                }
                if (selected[usoil3]) {
                    columns.push({ title: vRoot.$t('reportForm.oil3'), key: 'ad2', width: 90 })
                }
                if (selected[usoil4]) {
                    columns.push({ title: vRoot.$t('reportForm.oil4'), key: 'ad3', width: 90 })
                }
                if (selected[srcad0]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad0'), key: 'srcad0', width: 90 })
                }
                if (selected[srcad1]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad1'), key: 'srcad1', width: 90 })
                }
                if (selected[srcad2]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad2'), key: 'srcad2', width: 90 })
                }
                if (selected[srcad3]) {
                    columns.push({ title: vRoot.$t('reportForm.srcad3'), key: 'srcad3', width: 90 })
                }
                if (selected[altitude]) {
                    columns.push({ title: vRoot.$t('reportForm.altitude') + (isZh ? "(米)" : "(M)"), key: 'altitude', width: 90 })
                }
                if (selected[voltage]) {
                    columns.push({ title: vRoot.$t('reportForm.voltage') + '(V)', key: 'voltage', width: 90 })
                }


                me.initOilColumns();

                me.columns = columns.concat([
                    { title: vRoot.$t('reportForm.speed'), key: 'speed', width: 80 },
                    { title: vRoot.$t('reportForm.reissue'), key: 'reissue', width: 80 },
                    { title: vRoot.$t('reportForm.status'), key: 'strstatus', width: 160, },
                    {
                        title: vRoot.$t('reportForm.lon') + ',' + vRoot.$t('reportForm.lat'),
                        width: 210,
                        render: function(h, params) {
                            var row = params.row;
                            var callat = row.callat.toFixed(5);
                            var callon = row.callon.toFixed(5);

                            if (callat && callon) {
                                if (row.address == null) {

                                    return h('Button', {
                                        props: {
                                            type: 'error',
                                            size: 'small'
                                        },
                                        on: {
                                            click: function() {
                                                utils.getJiuHuAddressSyn(callon, callat, function(resp) {
                                                    if (resp && resp.address) {
                                                        vueInstanse.records[params.index].address = resp.address;
                                                        LocalCacheMgr.setAddress(callon, callat, resp.address);
                                                    }
                                                })
                                            }
                                        }
                                    }, callon + "," + callat)

                                } else {
                                    return h('Tooltip', {
                                        props: {
                                            content: row.address,
                                            placement: "top-start",
                                            maxWidth: 200
                                        },
                                    }, [
                                        h('Button', {
                                            props: {
                                                type: 'primary',
                                                size: 'small'
                                            }
                                        }, callon + "," + callat)
                                    ]);
                                }
                            } else {
                                return h('span', {}, '');
                            }
                        },
                    },
                ]);
            });
        }
    });
}






function dayOil(groupslist) {
    vueInstanse = new Vue({
        el: "#day-oil",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            groupslist: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 65 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 120 },
                { title: vRoot.$t('reportForm.date'), key: 'statisticsday', sortable: true, width: 110 },
                { title: vRoot.$t('reportForm.mileage') + '(km)', key: 'distance', width: 90 },
                { title: vRoot.$t('reportForm.oilConsumption') + '(L)', key: 'oil', width: 80 },
                { title: vRoot.$t('reportForm.fuelVolume') + '(L)', key: 'addoil', width: 165 },
                { title: vRoot.$t('reportForm.oilLeakage') + '(L)', key: 'leakoil', width: 165 },
                { title: vRoot.$t('reportForm.idleoil') + '(L)', key: 'idleoil', width: 165 },
                { title: vRoot.$t('reportForm.runoilper100km') + '(L)', key: 'runoilper100km', width: 140 },
                { title: vRoot.$t('reportForm.fuelConsumption100km') + '(L)', key: 'oilPercent', width: 165 },
                { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalnotrunningad', sortable: true, width: 145, },
                { title: vRoot.$t("reportForm.addnotrunningad") + '(L)', key: 'addnotrunningad', sortable: true, width: 155, },
                { title: vRoot.$t("reportForm.leaknotrunningad") + '(L)', key: 'leaknotrunningad', sortable: true, width: 155, },
            ],
            tableData: [],
            recvtime: [],
            oil: [],
            distance: [],
            currentIndex: 1,
        },
        mixins: [reportMixin],
        methods: {
            exportData: function() {


                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t('reportForm.date'),
                        vRoot.$t('reportForm.mileage') + '(km)',
                        vRoot.$t('reportForm.oilConsumption') + '(L)',
                        vRoot.$t('reportForm.fuelVolume') + '(L)',
                        vRoot.$t('reportForm.oilLeakage') + '(L)',
                        vRoot.$t('reportForm.idleoil') + '(L)',
                        vRoot.$t('reportForm.runoilper100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                        vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                        vRoot.$t("reportForm.addnotrunningad") + '(L)',
                        vRoot.$t("reportForm.leaknotrunningad") + '(L)',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.statisticsday);
                    itemArr.push(item.distance);
                    itemArr.push(item.oil);
                    itemArr.push(item.addoil);
                    itemArr.push(item.leakoil);
                    itemArr.push(item.idleoil);
                    itemArr.push(item.runoilper100km);
                    itemArr.push(item.oilPercent);
                    itemArr.push(item.totalnotrunningad);
                    itemArr.push(item.addnotrunningad);
                    itemArr.push(item.leaknotrunningad);
                    data.push(itemArr);
                });
                var options = {
                    title: (isZh ? '日行油耗-' : 'Daily fuel consumption-') + this.queryDeviceId,
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();

            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentPageIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            charts: function() {
                var dis = vRoot.$t('reportForm.mileage');
                var cotgas = vRoot.$t('reportForm.oilConsumption');
                var no_data = vRoot.$t('reportForm.empty');
                var option = {
                    tooltip: {
                        show: true,
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    legend: {
                        data: [dis, cotgas],
                        y: 13,
                        x: 'center'
                    },

                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        //boundaryGap : false,
                        axisLabel: {
                            show: true,
                            interval: 0, // {number}
                            rotate: 0,
                            margin: 8,
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        data: this.recvtime.length === 0 ? [no_data] : this.recvtime
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }],
                    series: [{
                            name: dis,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                                //悬浮式样式
                            },
                            data: this.distance
                        },
                        {
                            name: cotgas,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                            },
                            data: this.oil
                        }
                    ]
                };
                this.chartsIns.setOption(option, true);
            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 360;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") { return };
                var self = this;
                if (this.isSelectAll === null) {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                    return;
                };
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportOilDaily(), data, function(resp) {
                    self.loading = false;
                    self.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                    if (resp.status == 0) {
                        if (resp.records) {
                            var records = [],
                                oil = [],
                                distance = [],
                                recvtime = [];
                            resp.records.forEach(function(item) {
                                records = item.records;
                                records.forEach(function(record, index) {
                                    record.index = index + 1;
                                    record.devicename = '\t' + vstore.state.deviceInfos[self.queryDeviceId].devicename;
                                    record.distance = record.totaldistance;
                                    record.oil = record.totaloil / 100;
                                    record.addoil = record.addoil / 100;
                                    record.leakoil = record.leakoil / 100;
                                    record.idleoil = record.idleoil / 100;
                                    record.totalnotrunningad = record.totalnotrunningad / 100;
                                    record.addnotrunningad = record.addnotrunningad / 100;
                                    record.leaknotrunningad = record.leaknotrunningad / 100;
                                    record.runoilper100km = record.runoilper100km;

                                    record.distance = (record.distance / 1000).toFixed(2);
                                    // if (record.distance != 0) {
                                    // record.oilPercent = ((record.oil / (record.distance)) * 100).toFixed(2);
                                    record.oilPercent = record.oilper100km;
                                    // } else {
                                    //     record.oilPercent = 0;
                                    // }
                                    oil.push(record.oil);
                                    distance.push(record.distance);
                                    recvtime.push(record.statisticsday);
                                });
                            });
                            self.oil = oil;
                            self.distance = distance;
                            self.recvtime = recvtime;

                            self.records = records;
                            self.total = records.length;

                            self.currentPageIndex = 1;
                            self.tableData = records.slice(0, 20);
                            self.charts();
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            onSortChange: function(column) {

            }
        },
        mounted: function() {
            this.groupslist = groupslist;
            this.myChart = null;
            this.records = [];
            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.charts();

        }
    });
}

function fuelConsumptionTrend(groupslist) {
    vueInstanse = new Vue({
        el: "#fuel-consumption-trend",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            isSpin: false,
            activeTab: 'tabTotal',
            groupslist: [],
            allColumns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 70,
                }, {
                    title: vRoot.$t("alarm.action"),
                    width: 80,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getDetailTableData(params.row.deviceid, params.row);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.detailed") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid'
                },
                {
                    title: vRoot.$t("bgMgr.creater"),
                    key: 'creater'
                },
                {
                    title: vRoot.$t("monitor.groupName"),
                    key: 'groupname',
                    width: 100,
                },
                {
                    title: vRoot.$t("reportForm.selectTime"),
                    key: 'dateStr',
                },
                {
                    title: vRoot.$t("reportForm.workingHours") + '(H)',
                    key: 'duration',
                    // key: 'durationStr',
                    width: 160,
                    sortable: true,
                    // sortMethod: function(a, b, type) {
                    //     console.log(a, b);
                    // }
                },
                {
                    title: isZh ? '工作天数' : 'Working days',
                    key: 'count',
                    width: 110,
                    sortable: true,
                },
            ],
            allTableData: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 65 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 120 },
                { title: vRoot.$t('reportForm.date'), key: 'statisticsday', sortable: true, width: 110 },
                { title: vRoot.$t("reportForm.workingHours") + '(H)', key: 'totalacc', width: 140, sortable: true, },
                { title: vRoot.$t('reportForm.mileage') + '(km)', key: 'distance', width: 90 },
                { title: vRoot.$t('reportForm.oilConsumption') + '(L)', key: 'oil', width: 80 },
                { title: vRoot.$t('reportForm.fuelVolume') + '(L)', key: 'addoil', width: 165 },
                { title: vRoot.$t('reportForm.oilLeakage') + '(L)', key: 'leakoil', width: 165 },
                { title: vRoot.$t('reportForm.idleoil') + '(L)', key: 'idleoil', width: 165 },
                { title: vRoot.$t('reportForm.runoilper100km') + '(L)', key: 'runoilper100km', width: 140 },
                { title: vRoot.$t('reportForm.fuelConsumption100km') + '(L)', key: 'oilPercent', width: 165 },

                {
                    title: vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                    key: 'oilperhour',
                    width: 130,
                    sortable: true,
                },
                { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalnotrunningad', sortable: true, width: 145, },
                { title: vRoot.$t("reportForm.addnotrunningad") + '(L)', key: 'addnotrunningad', sortable: true, width: 155, },
                { title: vRoot.$t("reportForm.leaknotrunningad") + '(L)', key: 'leaknotrunningad', sortable: true, width: 155, },
            ],
            tableData: [],
            recvtime: [],
            dayNumberType: 10,
        },
        mixins: [treeMixin],
        methods: {
            handleSelectdDate(dayNumber) {
                var dayTime = 3600 * 24 * 1000;
                if (dayNumber == 10) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 11, timeDifference), DateFormat.longToDateStr(Date.now() - dayTime, timeDifference)];
                } else if (dayNumber == 30) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 31, timeDifference), DateFormat.longToDateStr(Date.now() - dayTime, timeDifference)];
                } else if (dayNumber == 60) {
                    this.dateVal = [DateFormat.longToDateStr(Date.now() - dayTime * 61, timeDifference), DateFormat.longToDateStr(Date.now() - dayTime, timeDifference)];
                }
                this.dayNumberType = dayNumber;
            },
            exportData: function() {
                if (this.activeTab == 'tabTotal') {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("bgMgr.creater"),
                            vRoot.$t("monitor.groupName"),
                            vRoot.$t("reportForm.selectTime"),
                            vRoot.$t("reportForm.workingHours"),
                            isZh ? '工作天数' : 'Working days',
                        ]
                    ];

                    this.allTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.creater);
                        itemArr.push(item.groupname);
                        itemArr.push(item.dateStr);
                        itemArr.push(item.durationStr);
                        itemArr.push(item.count);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.workStatistics'),
                        data: data,
                        dateRange: false,
                    }
                    new XlsxCls(options).exportExcel();
                } else {
                    var data = [
                        [
                            vRoot.$t('reportForm.index'),
                            vRoot.$t('alarm.devName'),
                            vRoot.$t('reportForm.date'),
                            vRoot.$t("reportForm.workingHours") + '(H)',
                            vRoot.$t('reportForm.mileage') + '(km)',
                            vRoot.$t('reportForm.oilConsumption') + '(L)',
                            vRoot.$t('reportForm.fuelVolume') + '(L)',
                            vRoot.$t('reportForm.oilLeakage') + '(L)',
                            vRoot.$t('reportForm.idleoil') + '(L)',
                            vRoot.$t('reportForm.runoilper100km') + '(L)',
                            vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                            vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                            vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                            vRoot.$t("reportForm.addnotrunningad") + '(L)',
                            vRoot.$t("reportForm.leaknotrunningad") + '(L)',
                        ]
                    ];
                    var deviceid = ' - ';
                    var len = this.tableData.length - 1;
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];
                        if (index == 0) {
                            deviceid += item.deviceid;
                        }

                        if (len == index) {
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push(isZh ? '总计' : 'Total');
                            itemArr.push(item.statisticsday);
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');

                        } else {
                            itemArr.push(index + 1);
                            itemArr.push(item.devicename);
                            itemArr.push(item.statisticsday);
                            itemArr.push(item.totalacc);
                            itemArr.push(item.distance);
                            itemArr.push(item.oil);
                            itemArr.push(item.addoil);
                            itemArr.push(item.leakoil);
                            itemArr.push(item.idleoil);
                            itemArr.push(item.runoilper100km);
                            itemArr.push(item.oilPercent);
                            itemArr.push(item.oilperhour);
                            itemArr.push(item.totalnotrunningad);
                            itemArr.push(item.addnotrunningad);
                            itemArr.push(item.leaknotrunningad);

                        }

                        data.push(itemArr);
                    });

                    var options = {
                        title: (vRoot.$t('reportForm.workStatistics')) + ' ' + deviceid,
                        data: data,
                    }

                    new XlsxCls(options).exportExcel();


                }

            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 190;
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            getDetailTableData: function(deviceid, row) {
                var records = deepClone(row.records);
                records.sort(function(a, b) {
                    return b.begintime - a.begintime;
                });
                var oil = [],
                    durationStr = 0,
                    distance = [],
                    recvtime = [],
                    totalaccs = [],
                    oilperhours = [],
                    idleoils = [];
                runoilper100kms = [];
                fuelConsumption100kms = [];


                records.forEach(function(record, index) {
                    // if (record.oilper100km > 0) {
                    var totalacc = Number((record.totalacc / 1000 / 3600).toFixed(2));
                    record.index = index + 1;
                    record.devicename = vstore.state.deviceInfos[deviceid].devicename;
                    record.distance = record.totaldistance;
                    record.oil = record.totaloil / 100;
                    record.addoil = record.addoil / 100;
                    record.leakoil = record.leakoil / 100;
                    record.idleoil = record.idleoil / 100;
                    record.totalnotrunningad = record.totalnotrunningad / 100;
                    record.addnotrunningad = record.addnotrunningad / 100;
                    record.leaknotrunningad = record.leaknotrunningad / 100;
                    // record.runoilper100km = record.runoilper100km;
                    record.totalacc = totalacc;
                    record.distance = (record.distance / 1000).toFixed(2);
                    record.oilPercent = record.oilper100km;
                    oil.push(record.oil);
                    durationStr += totalacc;
                    totalaccs.push(totalacc);
                    oilperhours.push(record.oilperhour);

                    distance.push(record.distance);
                    recvtime.push(record.statisticsday);
                    fuelConsumption100kms.push(record.oilPercent);
                    idleoils.push(record.idleoil);
                    runoilper100kms.push(record.runoilper100km);
                    record._highlight = false;

                    // }
                });

                this.oil = oil;
                this.distance = distance;
                this.recvtime = recvtime;
                this.idleoil = idleoils;
                this.runoilper100km = runoilper100kms;
                this.fuelConsumption100km = fuelConsumption100kms;
                this.totalaccs = totalaccs;
                this.oilperhours = oilperhours;


                records.push({
                    devicename: isZh ? '总计' : 'Total',
                    statisticsday: Number(durationStr.toFixed(2)) + (isZh ? '小时' : 'H'),
                })

                this.tableData = records;
                this.charts();
            },

            onClickQuery: function() {
                var self = this;
                this.activeTab = 'tabTotal';
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.tableData = [];
                var data = {
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: deviceids,
                };
                var dateStr = data.startday + ' - ' + data.endday;
                this.loading = true;
                utils.sendAjax(myUrls.reportOilDaily(), data, function(resp) {
                    self.loading = false;
                    // var saddress = utils.getMapLatLonAddress(resp.addressmap, record.slat, record.slon);
                    if (resp.status == 0) {
                        if (resp.records) {

                            resp.records.forEach(function(item, index) {

                                var device = vstore.state.deviceInfos[item.deviceid];
                                item.index = index + 1;
                                item.dateStr = dateStr;
                                item.creater = device.creater;
                                item.devicename = device.devicename;
                                item.groupname = utils.getGroupName(groupslist, item.deviceid);

                                var duration = 0;
                                var count = 0;
                                var records = item.records;
                                records.forEach(function(record) {

                                    duration += record.totalacc;
                                    if (record.totalacc > 0) {
                                        count++;
                                    } else {}
                                });

                                // totalOil = totalOil.toFixed(2);
                                // item.totalOil = totalOil;
                                item.count = count;
                                item.duration = Number((duration / 1000 / 3600).toFixed(2));
                                item.durationStr = utils.timeStamp(duration, isZh);
                            });

                            console.log('resp.records', resp.records);
                            self.allTableData = resp.records;

                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            onSortChange: function(column) {},
            charts: function() {

                var dis = vRoot.$t('reportForm.mileage');
                var cotgas = vRoot.$t('reportForm.oilConsumption');
                var no_data = vRoot.$t('reportForm.empty');
                var idleoil = vRoot.$t('reportForm.idleoil');
                var runoilper100km = vRoot.$t('reportForm.runoilper100km');
                var fuelConsumption100km = vRoot.$t('reportForm.fuelConsumption100km');
                var totalacc = vRoot.$t('reportForm.workingHours');
                var oilperhour = vRoot.$t('reportForm.fuelConsumptionHour');


                // { title: vRoot.$t('reportForm.idleoil') + '(L)', key: 'idleoil', width: 165 },
                // { title: vRoot.$t('reportForm.runoilper100km') + '(L)', key: 'runoilper100km', width: 140 },
                // { title: vRoot.$t('reportForm.fuelConsumption100km') + '(L)', key: 'oilPercent', width: 165 },
                var option = {
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v, a) {
                            var data = vRoot.$t('reportForm.date') + ': ' + v[0].name + '<br/>';
                            for (i in v) {
                                var seriesName = v[i].seriesName;
                                var value = v[i].value;
                                if (seriesName == dis) {
                                    data += seriesName + ' : ' + value + 'Km<br/>';
                                } else if (seriesName == oilperhour || seriesName == cotgas || seriesName == idleoil || seriesName == runoilper100km || seriesName == fuelConsumption100km) {
                                    data += seriesName + ' : ' + value + 'L<br/>';
                                } else if (seriesName == totalacc) {
                                    data += seriesName + ' : ' + value + 'H<br/>';
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [runoilper100km, fuelConsumption100km, dis, cotgas, idleoil, totalacc, oilperhour],
                        y: 13,
                        x: 'center',
                        selected: this.selectedLegend
                    },

                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime.length === 0 ? [no_data] : this.recvtime
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }],
                    series: [{
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#3CB371',
                            data: this.distance,
                            smooth: true,
                        },
                        {
                            name: cotgas,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#F0805A',
                            data: this.oil,
                            smooth: true,
                        },
                        {
                            name: idleoil,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#4876FF',
                            data: this.idleoil,
                            smooth: true,
                        },
                        {
                            name: runoilper100km,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#710000',
                            data: this.runoilper100km,
                            smooth: true,
                        },
                        {
                            name: fuelConsumption100km,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#C1232B',
                            data: this.fuelConsumption100km,
                            smooth: true,
                        },
                        {
                            name: totalacc,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#3C81BD',
                            data: this.totalaccs,
                            smooth: true,
                        },
                        {
                            name: oilperhour,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#ECC849',
                            data: this.oilperhours,
                            smooth: true,
                        },
                    ]
                };
                this.chartsIns.setOption(option, true);
            },
        },
        mounted: function() {
            this.records = [];
            var me = this;

            this.oil = [];
            this.distance = [];
            this.recvtime = [];
            this.idleoil = [];
            this.runoilper100km = [];
            this.fuelConsumption100km = [];
            this.totalaccs = [];
            this.oilperhours = [];

            if (isZh) {
                this.selectedLegend = {
                    '综合百公里油耗': false,
                    '里程': false,
                    '油耗': false,
                    '怠速油耗': false,
                    '工作时长': false,
                    '每小时油耗': false,
                }
            } else {
                this.selectedLegend = {
                    '100km Oil': false,
                    'Mileage': false,
                    'Daily Fuel Report': false,
                    'Idle Fuel': false,
                    'Working Duration': false,
                    'Fuel Per Hour': false,
                }
            }
            this.handleSelectdDate(10);
            this.groupslist = groupslist;
            this.records = [];
            this.chartsIns = echarts.init(document.getElementById('fuel-consumption-charts'));
            this.charts()

            this.chartsIns.on('legendselectchanged', function(param) {
                me.selectedLegend = param.selected;
            })

            this.queryDevicesTree();

        }
    });
}

function refuelingReport(groupslist) {
    vueInstanse = new Vue({
        el: "#refueling-report",
        i18n: utils.getI18n(),
        data: {
            oilIndexLabel: oilIndexLabel,
            loading: false,
            isSpin: false,
            markerModal: false,
            marker: '',
            tank: '0',
            activeTab: 'tabTotal',
            groupslist: [],
            allColumns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 70,
                }, {
                    title: vRoot.$t("alarm.action"),
                    width: 80,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getDetailTableData(params.row.deviceid, params.row);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.detailed") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid'
                },
                {
                    title: vRoot.$t("monitor.groupName"),
                    key: 'groupname',
                },
                {
                    title: vRoot.$t("reportForm.selectTime"),
                    key: 'dateStr',
                },
                {
                    title: vRoot.$t('reportForm.fuelVolume'),
                    key: 'totalOil',
                    width: 100,
                },
                {
                    title: vRoot.$t('reportForm.refuelingTimes'),
                    key: 'count',
                    width: 100,
                },
            ],
            allTableData: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 120 },
                { title: vRoot.$t('reportForm.oilChannel'), key: 'oilindexStr', width: 100 },
                { title: vRoot.$t('reportForm.soil'), key: 'soil', width: 136 },
                { title: vRoot.$t('reportForm.eoil'), key: 'eoil', width: 136 },
                { title: vRoot.$t('reportForm.fuelVolume') + '(L)', key: 'addoil', width: 120 },
                { title: vRoot.$t('reportForm.startDate'), key: 'begintimeStr', width: 160 },
                { title: vRoot.$t('reportForm.endDate'), key: 'endtimeStr', width: 160 },
                { title: isZh ? '距离(米)' : 'Distance(m)', key: 'distance', width: 100 },
                { title: isZh ? '平均速度(km/h)' : 'Average speed (km / h)', key: 'avgspeed', width: 140 },
                { title: isZh ? '时长(H)' : 'Duration(H)', key: 'durationStr', width: 110 },
                { title: isZh ? '阈值(L)' : 'Threshold', key: 'threshold', width: 100 },
                {
                    title: vRoot.$t('reportForm.saddress'),
                    width: 300,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.slat ? row.slat.toFixed(5) : null;
                        var lon = row.slon ? row.slon.toFixed(5) : null;
                        if (lat && lon) {
                            if (row.saddress == null) {
                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    var newRow = deepClone(row);
                                                    row.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('span', {}, row.saddress);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
                { title: vRoot.$t('monitor.remarks'), key: 'marker', width: 100 },
                { title: isZh ? '人工编辑' : 'Manual editing', key: 'mauneditStr', width: 100 },
                {
                    title: vRoot.$t('alarm.action'),
                    width: 180,
                    render: function(h, params) {
                        var row = params.row;
                        return h('div', {}, [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.queryTracks(row);
                                    }
                                }
                            }, vRoot.$t('reportForm.viewTrack')),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.marker = row.marker;
                                        vueInstanse.markerModal = true;
                                        editObjectRow = row;
                                    }
                                }
                            }, vRoot.$t('reportForm.editMarker'))
                        ])
                    }
                },
            ],
            tableData: [],
            recvtime: [],
            oil: [],
            trackDetailModal: false,
        },
        mixins: [treeMixin],
        methods: {
            rowClassName: function(row, index) {
                if (row.maunedit === 1) {
                    return 'demo-table-info-row';
                }
                return '';
            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('refueling-details-map');
            },
            queryTracks: function(row) {
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: row.begintimeStr,
                        endtime: row.endtimeStr,
                        interval: 5,
                        timezone: timeDifference
                    };
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.trackDetailModal = true;
                            utils.markersAndLineLayerToMap(me, records);
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            editOilRecord: function() {
                var me = this;
                var url = myUrls.editOilRecord();
                var data = {
                    oilrecordid: editObjectRow.oilrecordid,
                    marker: this.marker,
                    deviceid: editObjectRow.deviceid,
                    oilindex: editObjectRow.oilindex
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        me.$Message.success(isZh ? '编辑成功' : 'Edited successfully');
                        editObjectRow.marker = data.marker;
                        me.markerModal = false;
                    } else if (resp.status == 1) {
                        me.$Message.error(isZh ? '正在加油或者漏油中，请稍后备注' : 'Adding or leaking, please marker later');
                    }
                });
            },
            exportData: function() {
                if (this.activeTab == 'tabTotal') {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("monitor.groupName"),
                            vRoot.$t("reportForm.selectTime"),
                            vRoot.$t('reportForm.fuelVolume') + '(L)',
                            vRoot.$t('reportForm.refuelingTimes'),
                        ]
                    ];
                    this.allTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.groupname);
                        itemArr.push(item.dateStr);
                        itemArr.push(item.totalOil);
                        itemArr.push(item.count);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.addOilStatistics'),
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                } else {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t('reportForm.oilChannel'),
                            vRoot.$t('reportForm.soil'),
                            vRoot.$t('reportForm.eoil'),
                            vRoot.$t('reportForm.fuelVolume') + '(L)',
                            vRoot.$t('reportForm.startDate'),
                            vRoot.$t('reportForm.endDate'),
                            isZh ? '距离(米)' : 'Distance(m)',
                            isZh ? '平均速度(km/h)' : 'Average speed (km / h)',
                            isZh ? '时长(H)' : 'Duration(H)',
                            isZh ? '阈值(L)' : 'Threshold',
                            vRoot.$t('monitor.remarks'),
                            isZh ? '地址' : 'Address',
                            isZh ? '人工编辑' : 'Manual editing',
                        ]
                    ];
                    var len = this.tableData.length - 1;
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];

                        if (len == index) {
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push(item.addoil);
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                        } else {
                            itemArr.push(index + 1);
                            itemArr.push(item.devicename);
                            itemArr.push(item.oilindexStr);
                            itemArr.push(item.soil);
                            itemArr.push(item.eoil);
                            itemArr.push(item.addoil);
                            itemArr.push(item.begintimeStr);
                            itemArr.push(item.endtimeStr);
                            itemArr.push(item.distance);
                            itemArr.push(item.avgspeed);
                            itemArr.push(item.durationStr);
                            itemArr.push(item.threshold);
                            itemArr.push(item.marker);
                            itemArr.push(item.saddress);
                            itemArr.push(item.mauneditStr);
                        }


                        data.push(itemArr);
                    });

                    var options = {
                        title: vRoot.$t('reportForm.addOilDetailed'),
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                }

            },
            charts: function() {
                var cotgas = vRoot.$t('reportForm.fuelVolume');
                var no_data = vRoot.$t('reportForm.empty');
                var option = {
                    tooltip: {
                        show: true,
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    legend: {
                        data: [cotgas],
                        y: 13,
                        x: 'center'
                    },

                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        //boundaryGap : false,
                        axisLabel: {
                            show: true,
                            interval: 0, // {number}
                            rotate: 0,
                            margin: 8,
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        data: this.recvtime.length === 0 ? [no_data] : this.recvtime
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}L'
                        }
                    }],
                    series: [{
                        name: cotgas,
                        type: 'bar',
                        itemStyle: {
                            //默认样式
                            backgroundColor: '#000',
                            normal: {
                                label: {
                                    show: true,
                                    textStyle: {
                                        fontSize: '12',
                                        fontFamily: '微软雅黑',
                                        fontWeight: 'bold'
                                    }
                                }
                            },
                        },
                        color: '#135DB4',
                        data: this.oil
                    }]
                };
                this.chartsIns.setOption(option, true);

            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 415;
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            getDetailTableData: function(deviceid, row) {
                var records = deepClone(row.records);
                records.sort(function(a, b) {
                    return b.begintime - a.begintime;
                })
                records.forEach(function(record, index) {
                    record.index = index + 1;
                    var slat = record.slat.toFixed(5);
                    var slon = record.slon.toFixed(5);
                    var saddress = LocalCacheMgr.getAddress(slon, slat);
                    console.log('saddress', slat, slon, saddress);
                    if (saddress != null) {
                        record.saddress = saddress;
                    } else {
                        record.saddress = null;
                    };
                    var oil = record.eoil - record.soil;
                    oil = oil.toFixed(2);
                    record.devicename = vstore.state.deviceInfos[deviceid].devicename;
                    record.begintimeStr = DateFormat.longToLocalDateTimeStr(record.begintime);
                    record.endtimeStr = DateFormat.longToLocalDateTimeStr(record.endtime);
                    record.durationStr = (record.duration / 1000 / 3600).toFixed(2);
                    record.addoil = oil;
                    oilIndexLabel.forEach(function(item) {
                        if (item.value == record.oilindex) {
                            record.oilindexStr = item.label;
                        }
                    });
                    if (isZh) {
                        record.mauneditStr = record.maunedit == 1 ? '是' : '否'
                    } else {
                        record.mauneditStr = record.maunedit == 1 ? 'Yes' : 'NO'
                    }
                });
                records.push({
                    addoil: (isZh ? '总计:' : 'Total:') + row.totalOil
                })
                this.tableData = records;
            },
            onClickQuery: function() {
                var self = this;
                this.activeTab = 'tabTotal';
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.tableData = [];
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: deviceids,
                    oilstate: 1,
                    oilindex: Number(self.tank)
                };
                var dateStr = data.startday + ' - ' + data.endday;
                this.loading = true;
                utils.sendAjax(myUrls.reportOilRecord(), data, function(resp) {
                    self.loading = false;
                    self.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                    if (resp.status == 0) {
                        if (resp.records) {
                            var oilArr = [],
                                recvtime = [];
                            resp.records.forEach(function(item, index) {
                                item.index = index + 1;
                                item.dateStr = dateStr;
                                item.devicename = vstore.state.deviceInfos[item.deviceid].devicename;
                                item.groupname = utils.getGroupName(groupslist, item.deviceid);
                                var totalOil = 0;
                                var records = item.records;
                                records.forEach(function(record) {

                                    record.eoil = record.eoil / 100;
                                    record.soil = record.soil / 100;
                                    var oil = record.eoil - record.soil;
                                    totalOil += oil;


                                    var lat = record.slat.toFixed(5);
                                    var lon = record.slon.toFixed(5);
                                    var saddress = LocalCacheMgr.getAddress(lon, lat);
                                    if (saddress != null) {
                                        record.saddress = saddress;
                                    } else {
                                        utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                            if (resp && resp.address) {
                                                (function(lon, lat, record, resp) {
                                                    record.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                })(lon, lat, record, resp)
                                            }
                                        })
                                    };
                                });
                                totalOil = totalOil.toFixed(2);
                                if (totalOil > 0) {
                                    oilArr.push(totalOil);
                                    recvtime.push(item.devicename);
                                }
                                item.totalOil = totalOil;
                                item.count = records.length;
                            });

                            self.oil = oilArr;
                            self.recvtime = recvtime;
                            self.allTableData = resp.records;
                            self.charts();
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            onSortChange: function(column) {

            }
        },
        mounted: function() {
            var me = this;
            this.myChart = null;
            this.records = [];
            this.initMap();
            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.charts();
            this.queryDevicesTree();
        }
    });
}

function oilLeakageReport(groupslist) {
    vueInstanse = new Vue({
        el: "#oil-leakage-report",
        i18n: utils.getI18n(),
        data: {
            oilIndexLabel: oilIndexLabel,
            loading: false,
            isSpin: false,
            marker: '',
            markerModal: false,
            tank: '0',
            activeTab: 'tabTotal',
            groupslist: [],
            allColumns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 70,
                }, {
                    title: vRoot.$t("alarm.action"),
                    width: 80,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getDetailTableData(params.row.deviceid, params.row);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.detailed") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid'
                },
                {
                    title: vRoot.$t("monitor.groupName"),
                    key: 'groupname',
                },
                {
                    title: vRoot.$t("reportForm.selectTime"),
                    key: 'dateStr',
                },
                {
                    title: vRoot.$t('reportForm.oilLeakage') + '(L)',
                    key: 'totalOil',
                    width: 100
                },
                {
                    title: vRoot.$t('reportForm.oilLeakageTimes'),
                    key: 'count',
                    width: 100
                },
            ],
            allTableData: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 120 },
                { title: vRoot.$t('reportForm.oilChannel'), key: 'oilindexStr', width: 100 },
                { title: vRoot.$t('reportForm.lsoil'), key: 'soil', width: 136 },
                { title: vRoot.$t('reportForm.leoil'), key: 'eoil', width: 136 },
                {
                    title: vRoot.$t('reportForm.oilLeakage') + '(L)',
                    key: 'addoil',
                    width: 120
                },
                { title: vRoot.$t('reportForm.startDate'), key: 'begintimeStr', width: 160 },
                { title: vRoot.$t('reportForm.endDate'), key: 'endtimeStr', width: 160 },
                { title: isZh ? '距离(米)' : 'Distance(m)', key: 'distance', width: 100 },
                { title: isZh ? '平均速度(km/h)' : 'Average speed (km / h)', key: 'avgspeed', width: 130 },
                { title: isZh ? '时长(H)' : 'Duration(H)', key: 'durationStr', width: 110 },
                { title: isZh ? '阈值(L)' : 'Threshold', key: 'threshold', width: 100 },
                { title: isZh ? '人工编辑' : 'Manual editing', key: 'mauneditStr', width: 100 },
                {
                    title: vRoot.$t('reportForm.saddress'),
                    width: 300,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.slat ? row.slat.toFixed(5) : null;
                        var lon = row.slon ? row.slon.toFixed(5) : null;
                        if (lat && lon) {
                            if (row.saddress == null) {
                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    row.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('span', {}, row.saddress);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
                { title: vRoot.$t('monitor.remarks'), key: 'marker', width: 100 },
                {
                    title: vRoot.$t('alarm.action'),
                    width: 180,
                    render: function(h, params) {
                        var row = params.row;
                        return h('div', {}, [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        console.log(row)
                                        vueInstanse.queryTracks(row);
                                    }
                                }
                            }, vRoot.$t('reportForm.viewTrack')),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.marker = row.marker;
                                        vueInstanse.markerModal = true;
                                        editObjectRow = row;
                                    }
                                }
                            }, vRoot.$t('reportForm.editMarker')),

                        ])
                    }
                },
            ],
            tableData: [],
            recvtime: [],
            oil: [],
            trackDetailModal: false,
        },
        mixins: [treeMixin],
        methods: {
            rowClassName: function(row, index) {
                if (row.maunedit === 1) {
                    return 'demo-table-info-row';
                }
                return '';
            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('oil-leakage-details-map');
            },
            queryTracks: function(row) {
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: row.begintimeStr,
                        endtime: row.endtimeStr,
                        interval: 5,
                        timezone: timeDifference
                    };
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.trackDetailModal = true;
                            utils.markersAndLineLayerToMap(me, records);
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            editOilRecord: function() {
                var me = this;
                var url = myUrls.editOilRecord();
                var data = {
                    oilrecordid: editObjectRow.oilrecordid,
                    marker: this.marker,
                    deviceid: editObjectRow.deviceid,
                    oilindex: editObjectRow.oilindex
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        me.$Message.success(isZh ? '编辑成功' : 'Edited successfully');
                        editObjectRow.marker = data.marker;
                        me.markerModal = false;
                    } else if (resp.status == 1) {
                        me.$Message.error(isZh ? '正在加油或者漏油中，请稍后备注' : 'Adding or leaking, please marker later');
                    }
                });
            },
            exportData: function() {
                if (this.activeTab == 'tabTotal') {
                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("monitor.groupName"),
                            vRoot.$t("reportForm.selectTime"),
                            vRoot.$t('reportForm.oilLeakage') + '(L)',
                            vRoot.$t('reportForm.oilLeakageTimes'),
                        ]
                    ];
                    this.allTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.groupname);
                        itemArr.push(item.dateStr);
                        itemArr.push(item.totalOil);
                        itemArr.push(item.count);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.oilLeakageStatistics'),
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                } else {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t('reportForm.oilChannel'),
                            vRoot.$t('reportForm.lsoil'),
                            vRoot.$t('reportForm.leoil'),
                            vRoot.$t('reportForm.oilLeakage') + '(L)',
                            vRoot.$t('reportForm.startDate'),
                            vRoot.$t('reportForm.endDate'),
                            isZh ? '距离(米)' : 'Distance(m)',
                            isZh ? '平均速度(km/h)' : 'Average speed (km / h)',
                            isZh ? '时长(H)' : 'Duration(H)',
                            isZh ? '阈值(L)' : 'Threshold',
                            vRoot.$t('monitor.remarks'),
                            isZh ? '地址' : 'Address',
                            isZh ? '人工编辑' : 'Manual editing',
                        ]
                    ];
                    var len = this.tableData.length - 1;
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];

                        if (len == index) {
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push(item.addoil);
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                        } else {
                            itemArr.push(index + 1);
                            itemArr.push(item.devicename);
                            itemArr.push(item.oilindexStr);
                            itemArr.push(item.soil);
                            itemArr.push(item.eoil);
                            itemArr.push(item.addoil);
                            itemArr.push(item.begintimeStr);
                            itemArr.push(item.endtimeStr);
                            itemArr.push(item.distance);
                            itemArr.push(item.avgspeed);
                            itemArr.push(item.durationStr);
                            itemArr.push(item.threshold);
                            itemArr.push(item.marker);
                            itemArr.push(item.saddress);
                            itemArr.push(item.mauneditStr);
                        }


                        data.push(itemArr);
                    });

                    var options = {
                        title: vRoot.$t('reportForm.oilLeakageDetailed'),
                        data: data,
                        dateRange: this.queryDateRange,
                    }
                    new XlsxCls(options).exportExcel();

                }

            },
            charts: function() {
                var cotgas = vRoot.$t('reportForm.oilLeakage');
                var no_data = vRoot.$t('reportForm.empty');
                var option = {
                    tooltip: {
                        show: true,
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    legend: {
                        data: [cotgas],
                        y: 13,
                        x: 'center'
                    },

                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        //boundaryGap : false,
                        axisLabel: {
                            show: true,
                            interval: 0, // {number}
                            rotate: 0,
                            margin: 8,
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        data: this.recvtime.length === 0 ? [no_data] : this.recvtime
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}L'
                        }
                    }],
                    series: [{
                        name: cotgas,
                        type: 'bar',
                        itemStyle: {
                            //默认样式
                            backgroundColor: '#000',
                            normal: {
                                label: {
                                    show: true,
                                    textStyle: {
                                        fontSize: '12',
                                        fontFamily: '微软雅黑',
                                        fontWeight: 'bold'
                                    }
                                }
                            },
                        },
                        color: '#e4393c',
                        data: this.oil
                    }]
                };
                this.chartsIns.setOption(option, true);

            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 415;
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            getDetailTableData: function(deviceid, row) {
                var records = row.records;
                records.sort(function(a, b) {
                    return b.begintime - a.begintime;
                })
                records.forEach(function(record, index) {
                    record.index = index + 1;
                    var slat = record.slat.toFixed(5);
                    var slon = record.slon.toFixed(5);
                    var saddress = LocalCacheMgr.getAddress(slon, slat);
                    if (saddress != null) {
                        record.saddress = saddress;
                    } else {
                        record.saddress = null;
                    };
                    var oil = record.eoil - record.soil;
                    oil = oil.toFixed(2);
                    record.devicename = vstore.state.deviceInfos[deviceid].devicename;
                    record.begintimeStr = DateFormat.longToLocalDateTimeStr(record.begintime);
                    record.endtimeStr = DateFormat.longToLocalDateTimeStr(record.endtime);
                    record.addoil = oil;
                    oilIndexLabel.forEach(function(item) {
                        if (item.value == record.oilindex) {
                            record.oilindexStr = item.label;
                        }
                    });
                    record.durationStr = (record.duration / 1000 / 3600).toFixed(2);
                    if (isZh) {
                        record.mauneditStr = record.maunedit == 1 ? '是' : '否'
                    } else {
                        record.mauneditStr = record.maunedit == 1 ? 'Yes' : 'NO'
                    }
                });
                records.push({
                    addoil: (isZh ? '总计:' : 'Total:') + row.totalOil
                })
                this.tableData = records;
            },
            onClickQuery: function() {
                var self = this;
                this.activeTab = 'tabTotal';
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.tableData = [];
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: deviceids,
                    oilstate: -1,
                    oilindex: Number(self.tank)
                };
                var dateStr = data.startday + ' - ' + data.endday;
                this.loading = true;
                utils.sendAjax(myUrls.reportOilRecord(), data, function(resp) {
                    self.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                    self.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {
                            var oilArr = [],
                                recvtime = [];
                            resp.records.forEach(function(item, index) {
                                item.index = index + 1;
                                item.dateStr = dateStr;
                                item.devicename = vstore.state.deviceInfos[item.deviceid].devicename;
                                item.groupname = utils.getGroupName(groupslist, item.deviceid);
                                var totalOil = 0;
                                var records = item.records;
                                records.forEach(function(record) {

                                    record.eoil = record.eoil / 100;
                                    record.soil = record.soil / 100;
                                    var oil = record.soil - record.eoil;
                                    totalOil += oil;


                                    var lat = record.slat.toFixed(5);
                                    var lon = record.slon.toFixed(5);
                                    var saddress = LocalCacheMgr.getAddress(lon, lat);
                                    if (saddress != null) {
                                        record.saddress = saddress;
                                    } else {
                                        utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                            if (resp && resp.address) {
                                                (function(lon, lat, record, resp) {
                                                    record.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                })(lon, lat, record, resp)
                                            }
                                        })
                                    };
                                });
                                totalOil = totalOil.toFixed(2);
                                if (totalOil > 0) {
                                    oilArr.push(totalOil);
                                    recvtime.push(item.devicename);
                                }
                                item.totalOil = totalOil;
                                item.count = records.length;
                            });

                            self.oil = oilArr;
                            self.recvtime = recvtime;
                            self.allTableData = resp.records;
                            self.charts();
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            onSortChange: function(column) {

            }
        },
        mounted: function() {
            var me = this;
            this.myChart = null;
            this.records = [];
            this.initMap();
            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.charts();
            this.queryDevicesTree();

        }
    });

}


function powerWaste(groupslist) {
    vueInstanse = new Vue({
        el: "#power-waste",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            groupslist: [],
        },
        mixins: [reportMixin],
        methods: {
            onClickQuery: function() {
                var me = this;
                if (!this.queryDeviceId) {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                    return;
                };
                var data = {
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                    offset: timeDifference
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportOilConsumptionRate(), data, function(resp) {
                    me.loading = false;
                    if (resp.status == 0) {
                        var record = resp.records[0];
                        if (record) {
                            var records = record.records;
                            var recvtime = [];
                            var oilrates = [];
                            var speeds = [];
                            var altitudes = [];
                            var voltages = [];
                            var mileages = [];
                            var oils = [];
                            var devStates = [];
                            var firstMile = 0;
                            records.forEach(function(item, index) {
                                if (index == 0) {
                                    firstMile = item.totaldistance;
                                };
                                oilrates.push(item.oilrate);
                                speeds.push(item.speed / 1000);
                                altitudes.push(item.altitude);
                                voltages.push(item.voltage / 100.0);
                                oils.push(item.totalad / 100);
                                devStates.push(isZh ? item.strstatus : item.strstatusen);
                                recvtime.push(DateFormat.longToLocalDateTimeStr(item.updatetime));
                                mileages.push((item.totaldistance - firstMile) / 1000);
                            })
                            me.recvtime = recvtime;
                            me.oilrates = oilrates;
                            me.speeds = speeds;
                            me.altitudes = altitudes;
                            me.voltages = voltages;
                            me.mileages = mileages;
                            me.devStates = devStates;
                            me.oils = oils;
                            me.chartsIns1.setOption(me.getChartsOption());
                        } else {
                            me.$Message.error(me.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(resp.cause);
                    }
                })
            },
            getChartsOption: function() {
                var time = vRoot.$t('reportForm.time');
                var oilrate = vRoot.$t('reportForm.oilrate');
                var speed = vRoot.$t('reportForm.speed');
                var altitude = vRoot.$t('reportForm.altitude');
                var voltage = vRoot.$t('reportForm.voltage');
                var mileage = vRoot.$t('reportForm.mileage');
                var status = vRoot.$t('reportForm.status');
                var oil = vRoot.$t('reportForm.oil');

                return {
                    title: {
                        text: oilrate,
                        x: 'left',
                        textStyle: {
                            fontSize: 16,
                            fontWeight: 'bolder',
                            color: '#333'
                        }
                    },
                    legend: {
                        data: [mileage, oil, oilrate, speed, altitude, voltage, ]
                    },
                    grid: {
                        top: 30,
                        left: 60,
                        right: 60,
                        bottom: 40,
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var axisValue = v[0].axisValue;
                            var data = time + ' : ' + axisValue + '<br/>';
                            for (i in v) {
                                var seriesName = v[i].seriesName;
                                if (seriesName) {
                                    if (seriesName == mileage) {
                                        data += seriesName + ' : ' + v[i].value + 'km' + '<br/>';
                                    } else if (seriesName == oilrate || seriesName == oil) {
                                        data += seriesName + ' : ' + v[i].value + 'L' + '<br/>';
                                    } else if (seriesName == speed) {
                                        data += seriesName + ' : ' + v[i].value + 'km/h' + '<br/>';
                                    } else if (seriesName == altitude) {
                                        data += seriesName + ' : ' + v[i].value + 'M' + '<br/>';
                                    } else if (seriesName == voltage) {
                                        data += seriesName + ' : ' + v[i].value + 'V' + '<br/>';
                                    } else {
                                        data += seriesName + ' : ' + v[i].value;
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    xAxis: {
                        type: 'category',
                        data: this.recvtime
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                            name: mileage,
                            data: this.mileages,
                            type: 'line',
                            smooth: true,
                            color: '#3CB371'
                        },
                        {
                            name: oil,
                            data: this.oils,
                            type: 'line',
                            smooth: true,
                            color: '#C1232B'
                        }, {
                            name: oilrate,
                            data: this.oilrates,
                            type: 'line',
                            smooth: true,
                            color: '#FF4500'
                        },
                        {
                            name: speed,
                            data: this.speeds,
                            type: 'line',
                            smooth: true,
                            color: '#4876FF'
                        },
                        {
                            name: altitude,
                            data: this.altitudes,
                            type: 'line',
                            smooth: true,
                            color: '#881280'
                        },
                        {
                            name: voltage,
                            data: this.voltages,
                            type: 'line',
                            smooth: true,
                            color: '#710000'
                        },
                        {
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates,
                            smooth: true,
                        },

                    ]

                };
            },
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.recvtime = [];
            this.oilrates = [];
            this.speeds = [];
            this.altitudes = [];
            this.voltages = [];
            this.mileages = [];
            this.devStates = [];
            this.oils = [];
            this.chartsIns1 = echarts.init(document.getElementById('charts1'));
            setTimeout(function() {
                me.chartsIns1.setOption(me.getChartsOption());
            }, 500);

            window.onresize = function() {
                me.chartsIns1.resize();
            }
        }
    });

}




function oilWorkingHours(groupslist) {
    vueInstanse = new Vue({
        el: "#oil-working-hours",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            isSpin: false,
            tank: '0',
            startDate: DateFormat.longToDateStr(Date.now(), timeDifference),
            startTime: '00:00:00',
            endDate: DateFormat.longToDateStr(Date.now(), timeDifference),
            endTime: '23:59:59',
            options: {
                disabledDate: function(date) {
                    return date && date.valueOf() > Date.now();
                }
            },
            dateTimeRangeVal: [DateFormat.longToDateStr(Date.now(), timeDifference) + " 00:00:00", DateFormat.longToDateStr(Date.now(), timeDifference) + " 23:59:59"],
            groupslist: [],
            columns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 65,
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename',
                    width: 125,
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                    width: 125,
                },
                {
                    title: vRoot.$t('reportForm.mileage') + '(km)',
                    key: 'totaldistance',
                    width: 90,
                },
                {
                    title: vRoot.$t("reportForm.oilConsumption") + '(L)',
                    key: 'totaloil',
                    width: 120,

                },
                {
                    title: vRoot.$t("reportForm.workingHours") + '(H)',
                    key: 'totalacc',
                    width: 120,

                },
                { title: vRoot.$t('reportForm.idleoil') + '(L)', key: 'idleoil', width: 120, },
                { title: vRoot.$t('reportForm.runoilper100km') + '(L)', key: 'runoilper100km', width: 140 },
                {
                    title: vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                    key: 'oilper100km',
                    width: 160,
                },
                {
                    title: vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                    key: 'oilperhour',
                    width: 120,
                },
                {
                    title: vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                    key: 'averagespeed',
                    width: 130,
                },
                { title: vRoot.$t("reportForm.totalnotrunningad") + '(L)', key: 'totalnotrunningad', sortable: true, width: 145, },
                { title: vRoot.$t("reportForm.addnotrunningad") + '(L)', key: 'addnotrunningad', sortable: true, width: 155, },
                { title: vRoot.$t("reportForm.leaknotrunningad") + '(L)', key: 'leaknotrunningad', sortable: true, width: 155, },
            ],
            tableData: [],
            oil: [],
            recvtime: [],
            chartDataList: [],
        },
        mixins: [treeMixin],
        methods: {
            onTimeRangeChange: function(timeRange) {
                this.dateTimeRangeVal = timeRange;
            },
            exportData: function() {

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t('reportForm.mileage') + '(km)',
                        vRoot.$t("reportForm.oilConsumption") + '(L)',
                        vRoot.$t("reportForm.workingHours") + '(H)',
                        vRoot.$t('reportForm.idleoil') + '(L)',
                        vRoot.$t('reportForm.runoilper100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumption100km') + '(L)',
                        vRoot.$t('reportForm.fuelConsumptionHour') + '(L)',
                        vRoot.$t('reportForm.averageSpeed') + '(km/h)',
                        vRoot.$t("reportForm.totalnotrunningad") + '(L)',
                        vRoot.$t("reportForm.addnotrunningad") + '(L)',
                        vRoot.$t("reportForm.leaknotrunningad") + '(L)',
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.totaldistance);
                    itemArr.push(item.totaloil);
                    itemArr.push(item.totalacc);
                    itemArr.push(item.idleoil);
                    itemArr.push(item.runoilper100km);
                    itemArr.push(item.oilper100km);
                    itemArr.push(item.oilperhour);
                    itemArr.push(item.averagespeed);
                    itemArr.push(item.totalnotrunningad);
                    itemArr.push(item.addnotrunningad);
                    itemArr.push(item.leaknotrunningad);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.oilWorkingHours'),
                    data: data,
                    dateRange: this.begintimeAndEndtime,
                }
                new XlsxCls(options).exportExcel();
            },
            getChartsOption: function(deviceNames, oils, disArr, hours) {

                var dis = vRoot.$t('reportForm.mileage');
                var cotgas = vRoot.$t('reportForm.oilConsumption');
                var workingHours = vRoot.$t("reportForm.workingHours") + '(H)';

                return {
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v, a) {
                            var data = v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName == dis) {
                                    data += v[i].seriesName + ' : ' + v[i].value + 'km<br/>';
                                } else if (v[i].seriesName == cotgas) {
                                    data += v[i].seriesName + ' : ' + v[i].value + 'L<br/>';
                                } else if (v[i].seriesName == workingHours) {
                                    data += v[i].seriesName + ' : ' + utils.timeStamp(v[i].value * 1000 * 3600) + '<br/>';
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [dis, cotgas, workingHours],
                        y: 13,
                        x: 'center'
                    },

                    grid: {
                        x: 100,
                        y: 40,
                        x2: 80,
                        y2: 30
                    },
                    xAxis: [{
                        type: 'category',
                        //boundaryGap : false,
                        axisLabel: {
                            show: true,
                            interval: 0, // {number}
                            rotate: 0,
                            margin: 8,
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        data: deviceNames
                    }],
                    yAxis: [{
                        type: 'value',
                        position: 'bottom',
                        nameLocation: 'end',
                        boundaryGap: [0, 0.2],
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }],
                    series: [{
                            name: dis,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                                //悬浮式样式
                            },
                            data: disArr
                        },
                        {
                            name: cotgas,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                            },
                            data: oils
                        },
                        {
                            name: workingHours,
                            type: 'bar',
                            itemStyle: {
                                //默认样式
                                normal: {
                                    label: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '12',
                                            fontFamily: '微软雅黑',
                                            fontWeight: 'bold'
                                        }
                                    }
                                }
                            },
                            data: hours
                        },
                    ]
                };

            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 365;
            },
            onClickQuery: function() {
                var self = this;
                this.activeTab = 'tabTotal';
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }


                var begintime = DateFormat.longToDateStr(this.startDate.getTime(), timeDifference) + ' ' + this.startTime;
                var endtime = DateFormat.longToDateStr(this.endDate.getTime(), timeDifference) + ' ' + this.endTime;

                if (new Date(begintime).getTime() > new Date(endtime).getTime()) {
                    this.$Message.error(this.$t('videoback.downloadTips3'));
                    return;
                }

                this.begintimeAndEndtime = begintime + '-' + endtime;

                this.tableData = [];
                this.chartDataList = [];
                var data = {
                    // username: vstore.state.userName,
                    begintime: begintime,
                    endtime: endtime,
                    timezone: timeDifference,
                    devices: deviceids,
                    oilindex: Number(this.tank)
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportOilManHour(), data, function(resp) {
                    self.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {
                            var chartDataList = [];

                            // render: function(h, pramas) {
                            //     var row = pramas.row; totaldistance
                            //     return h('sapn', {}, (row.totaldistance / 1000).toFixed(2));
                            // },
                            // render: function(h, pramas) {
                            //     var row = pramas.row; totaloil
                            //     return h('sapn', {}, (row.totaloil / 100).toFixed(2));
                            // },

                            // render: function(h, pramas) {
                            //     var row = pramas.row;  totalacc
                            //     return h('sapn', {}, utils.timeStamp(row.totalacc));
                            // },

                            resp.records.forEach(function(item, index) {

                                item.index = index + 1;
                                item.devicename = vstore.state.deviceInfos[item.deviceid] ? vstore.state.deviceInfos[item.deviceid].devicename : item.deviceid;
                                if (index % 4 == 0) {
                                    chartDataList.push({
                                        data: [],
                                        oil: [],
                                        dis: [],
                                        hours: [],
                                    })
                                }
                                var len = chartDataList.length - 1;
                                var totalacc = (item.totalacc / 1000 / 3600).toFixed(2);
                                item.idleoil = item.idleoil / 100;
                                item.runoilper100km = item.runoilper100km;
                                item.totaldistance = (item.totaldistance / 1000).toFixed(2)
                                item.totalacc = totalacc
                                item.totaloil = item.totaloil / 100;
                                item.totalnotrunningad = item.totalnotrunningad / 100;
                                item.addnotrunningad = item.addnotrunningad / 100;
                                item.leaknotrunningad = item.leaknotrunningad / 100;

                                chartDataList[len].data.push(item.devicename);
                                chartDataList[len].oil.push(item.totaloil);
                                chartDataList[len].dis.push(Number(item.totaldistance));
                                chartDataList[len].hours.push(Number(totalacc));

                                if (item.totaldistance == 0 || totalacc == 0) {
                                    item.averagespeed = 0
                                } else {
                                    item.averagespeed = (Number(item.totaldistance) / Number(totalacc)).toFixed(2);
                                }


                            });

                            self.tableData = resp.records;
                            self.chartDataList = chartDataList;


                            setTimeout(function() {
                                self.initCharts();
                            }, 300);
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            initCharts: function() {
                var index = 0;
                var len = this.chartDataList.length;
                while (index < len) {
                    var chartsIns = echarts.init(document.getElementById('charts' + index));
                    var data = this.chartDataList[index]
                    chartsIns.setOption(this.getChartsOption(data.data, data.oil, data.dis, data.hours), true);

                    // chartDataList[len].data.push(item.devicename);
                    // chartDataList[len].oil.push(item.totaloil);
                    // chartDataList[len].dis.push(item.totaldistance);
                    // chartDataList[len].hours.push(item.totalacc);

                    index++;
                }
            }
        },
        mounted: function() {
            this.myChart = null;
            this.records = [];
            this.queryDevicesTree();
        }
    });
}


function idleReport(groupslist) {

    vueInstanse = new Vue({
        el: "#idle-report",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            isSpin: false,
            markerModal: false,
            marker: '',
            tank: '0',
            intervalminutes: '5',
            activeTab: 'tabTotal',
            groupslist: [],
            allColumns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 70,
                }, {
                    title: vRoot.$t("alarm.action"),
                    width: 80,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getDetailTableData(params.row.deviceid, params.row);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.detailed") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid'
                },
                {
                    title: vRoot.$t("monitor.groupName"),
                    key: 'groupname',
                    width: 100,
                },
                {
                    title: vRoot.$t("reportForm.selectTime"),
                    key: 'dateStr',
                },
                { title: isZh ? '怠速时长' : 'Duration', key: 'durationStr', width: 160 },
                {
                    title: vRoot.$t("reportForm.idleTimes"),
                    key: 'count',
                    width: 100,
                },
            ],
            allTableData: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 150 },
                { title: isZh ? '怠速时长' : 'Duration', key: 'durationStr', width: 110 },
                { title: vRoot.$t('reportForm.startDate'), width: 160, key: 'begintimeStr', width: 170, },
                { title: vRoot.$t('reportForm.endDate'), width: 160, key: 'endtimeStr', width: 170, },
                {
                    title: vRoot.$t('reportForm.saddress'),
                    width: 300,
                    key: 'saddress',
                },
                {
                    title: vRoot.$t('reportForm.eaddress'),
                    width: 300,
                    key: 'eaddress',
                },
                {
                    title: vRoot.$t('alarm.action'),
                    width: 100,
                    render: function(h, params) {
                        var row = params.row;
                        return h('div', {}, [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.queryTracks(row);
                                    }
                                }
                            }, vRoot.$t('reportForm.viewTrack')),
                        ])
                    }
                },
            ],
            tableData: [],
            recvtime: [],
            interval: '100',
            trackDetailModal: false,
        },
        mixins: [treeMixin],
        methods: {
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('idle-details-map');
            },
            queryTracks: function(row) {
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: row.begintimeStr,
                        endtime: row.endtimeStr,
                        interval: 5,
                        timezone: timeDifference
                    };
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.trackDetailModal = true;
                            utils.markersAndLineLayerToMap(me, records);
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            editOilRecord: function() {
                var me = this;
                var url = myUrls.editOilRecord();
                var data = {
                    oilrecordid: editObjectRow.oilrecordid,
                    marker: this.marker,
                    deviceid: editObjectRow.deviceid,
                    oilindex: editObjectRow.oilindex
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        me.$Message.success(isZh ? '编辑成功' : 'Edited successfully');
                        editObjectRow.marker = data.marker;
                        me.markerModal = false;
                    } else if (resp.status == 1) {
                        me.$Message.error(isZh ? '正在加油或者漏油中，请稍后备注' : 'Adding or leaking, please marker later');
                    }
                });
            },
            exportData: function() {
                if (this.activeTab == 'tabTotal') {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("monitor.groupName"),
                            vRoot.$t("reportForm.selectTime"),
                            isZh ? '怠速时长' : 'Duration',
                            isZh ? '怠速时长(H)' : 'Duration(H)',
                            vRoot.$t("reportForm.idleTimes"),
                        ]
                    ];
                    this.allTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.groupname);
                        itemArr.push(item.dateStr);
                        itemArr.push(item.durationStr);
                        itemArr.push(item.duration);
                        itemArr.push(item.count);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.idleStatistics'),
                        data: data,
                        dateRange: false,
                    }
                    new XlsxCls(options).exportExcel();
                } else {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),

                            isZh ? '怠速时长' : 'Duration',
                            isZh ? '怠速时长(H)' : 'Duration(H)',
                            vRoot.$t('reportForm.startDate'),
                            vRoot.$t('reportForm.endDate'),
                            vRoot.$t('reportForm.saddress'),
                            vRoot.$t('reportForm.eaddress'),
                        ]
                    ];
                    var deviceid = ' - ';
                    var len = this.tableData.length - 1;
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];
                        if (index == 0) {
                            deviceid += item.deviceid;
                        }

                        if (len == index) {

                            itemArr.push(isZh ? '总计' : 'Total');
                            itemArr.push('');
                            itemArr.push(item.durationStr);
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');

                        } else {
                            itemArr.push(index + 1);
                            itemArr.push(item.devicename);
                            itemArr.push(item.durationStr);
                            itemArr.push(item.duration);
                            itemArr.push(item.begintimeStr);
                            itemArr.push(item.endtimeStr);
                            itemArr.push(item.saddress);
                            itemArr.push(item.eaddress);
                        }

                        data.push(itemArr);
                    });

                    var options = {
                        title: vRoot.$t('reportForm.idleDetailed') + deviceid,
                        data: data,
                    }
                    new XlsxCls(options).exportExcel();


                }

            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 190;
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            getDetailTableData: function(deviceid, row) {
                var records = deepClone(row.records);
                records.sort(function(a, b) {
                    return b.begintime - a.begintime;
                })
                records.forEach(function(record, index) {
                    record.index = index + 1;

                    if (record.slat == 0) {
                        record.slat = record.elat;
                    }
                    if (record.slon == 0) {
                        record.slon = record.elon;
                    }

                    record.deviceid = deviceid;
                    record.devicename = vstore.state.deviceInfos[deviceid].devicename;
                    record.begintimeStr = DateFormat.longToLocalDateTimeStr(record.begintime);
                    record.endtimeStr = DateFormat.longToLocalDateTimeStr(record.endtime);
                    record.duration = ((record.endtime - record.begintime) / 1000 / 3600).toFixed(2);;
                    record.durationStr = utils.timeStamp(record.endtime - record.begintime, isZh);


                });
                records.push({
                    devicename: isZh ? '总计' : 'Total',

                    durationStr: row.durationStr,
                    begintimeStr: '',
                    endtimeStr: '',
                })
                this.tableData = records;



                this.reportAccTime(deviceid);
            },
            reportAccTime: function(deviceid) {
                var me = this;
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [deviceid],
                };

                // this.loading = true;
                utils.sendAjax(myUrls.reportAccTime(), data, function(resp) {
                    // me.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {
                            var records = [],
                                voltages = [],
                                speeds = [],
                                distances = [],
                                recvtime = [],
                                idleArr = [],
                                accStates = [],
                                devStates = [];
                            firstDistance = 0;
                            resp.records.forEach(function(item) {
                                records = item.records;
                                records.forEach(function(record, index) {

                                    if (index == 0) {
                                        firstDistance = record.totaldistance;
                                    };
                                    voltages.push(record.voltage / 100);
                                    var totalad = record.totalad;

                                    record.totalad = totalad / 100;

                                    record.speed = (record.speed / 1000).toFixed(2);
                                    record.updatetimeStr = DateFormat.longToLocalDateTimeStr(record.updatetime);
                                    // record.arrivedtimeStr = DateFormat.longToLocalDateTimeStr(record.arrivedtime);
                                    accStates.push(utils.getAccSwitchStatusStr(record));
                                    devStates.push(isZh ? record.strstatus : record.strstatusen);

                                    speeds.push(record.speed);
                                    record.totaldistance = ((record.totaldistance - firstDistance) / 1000).toFixed(2);
                                    distances.push(record.totaldistance);
                                    recvtime.push(record.updatetimeStr);
                                    var isIdle = me.isIdleTrack(record);
                                    if (isIdle) {
                                        idleArr.push(record.totaldistance);
                                    } else {
                                        idleArr.push('-');
                                    }

                                });
                            });

                            me.recvtime = recvtime;
                            me.speeds = speeds;
                            me.distances = distances;
                            me.idleArr = idleArr;
                            me.devStates = devStates;
                            me.accStates = accStates;
                            me.voltages = voltages;
                            me.charts();
                        } else {
                            me.$Message.error(me.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(resp.cause);
                    }
                }, function() {
                    me.loading = false;
                })

            },

            isIdleTrack: function(track) {
                var isIdle = false;
                var status = track.status;
                //0 0：未启用Acc 2:ACC 关；3： ACC 开
                var acc = (status & 0x03);
                if (acc == 0x03) {
                    var speed = track.speed;
                    if (speed <= 0) {
                        isIdle = true;
                    }
                }
                return isIdle;
            },
            onClickQuery: function() {
                var self = this;
                this.activeTab = 'tabTotal';
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.tableData = [];
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: deviceids,
                    intervalminutes: Number(this.intervalminutes)
                };
                var dateStr = data.startday + ' - ' + data.endday;
                this.loading = true;
                utils.sendAjax(myUrls.reportDriveIdle(), data, function(resp) {
                    self.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {

                            resp.records.forEach(function(item, index) {
                                item.index = index + 1;
                                item.dateStr = dateStr;
                                item.devicename = vstore.state.deviceInfos[item.deviceid].devicename;
                                item.groupname = utils.getGroupName(groupslist, item.deviceid);
                                var totalOil = 0;
                                var records = item.records;
                                var duration = 0;
                                records.forEach(function(record) {

                                    record.eoil = record.eoil / 100;
                                    record.soil = record.soil / 100;
                                    var oil = record.eoil - record.soil;
                                    totalOil += Math.abs(oil);

                                    duration += record.endtime - record.begintime;

                                    var saddress = utils.getMapLatLonAddress(resp.addressmap, record.slat, record.slon);
                                    var eaddress = utils.getMapLatLonAddress(resp.addressmap, record.elat, record.elon);

                                    record.saddress = saddress;
                                    record.eaddress = eaddress;

                                });

                                totalOil = totalOil.toFixed(2);
                                item.totalOil = totalOil;
                                item.count = records.length;
                                item.duration = (duration / 1000 / 3600).toFixed(2);
                                item.durationStr = utils.timeStamp(duration, isZh);
                            });

                            self.allTableData = resp.records;

                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            onSortChange: function(column) {

            },
            charts: function() {
                var totoil = vRoot.$t('reportForm.oil');
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');

                var status = vRoot.$t('reportForm.status');
                var idle = isZh ? '怠速' : 'Idle';
                var accstatus = isZh ? 'Acc状态' : 'Acc State';
                var voltage = isZh ? '电压' : 'Voltage';

                console.log('this.totalad', this.totalad);
                var option = {

                    grid: {
                        top: 30,
                        left: 60,
                        right: 60,
                        bottom: 40,
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';

                            for (i in v) {
                                var seriesName = v[i].seriesName;
                                if (seriesName && seriesName != time) {
                                    if (seriesName == dis) {
                                        var currentDistance = v[i].value;
                                        var totalDistance = ((Number(currentDistance) + firstDistance) / 1000).toFixed(2);
                                        data += seriesName + ' : ' + currentDistance + "(T:" + totalDistance + ")" + 'km<br/>';

                                    } else if (seriesName == idle) {
                                        if (v[i].value != '-') {
                                            data += seriesName + ' : ' + v[i].value + 'Km<br/>';
                                        } else {
                                            data += seriesName + ' : ' + v[i].value + '<br/>';
                                        }
                                    } else if (seriesName == speed) {
                                        data += seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else if (seriesName == voltage) {
                                        data += seriesName + ' : ' + v[i].value + 'V<br/>';
                                    } else {
                                        data += seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, idle],
                        selected: this.selectedLegend,
                        x: 'left',
                        // width: 600,
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        //fillerColor:'rgb(244,129,38,0.8)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                            name: '', //totoil + '/' + speed
                            type: 'value',
                            nameTextStyle: 10,
                            nameGap: 5,

                        },
                        {
                            name: '', //dis
                            type: 'value',
                            nameTextStyle: 10,
                            nameGap: 2,
                            // min: this.disMin,
                            axisLabel: {
                                formatter: '{value} km',
                            },
                            axisTick: {
                                show: false
                            }
                        }
                    ],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.speeds
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distances
                        }, {
                            smooth: true,
                            name: idle,
                            type: 'line',
                            symbol: 'none',
                            color: 'red',
                            yAxisIndex: 1,
                            data: this.idleArr,
                        },

                        {
                            name: accstatus,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.accStates,
                            smooth: true,
                        },
                        {
                            name: voltage,
                            type: 'line',
                            symbol: 'none',
                            color: '#e2e2e2',
                            data: this.voltages,
                            smooth: true,
                        },
                        {
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#010101',
                            data: this.devStates,
                            smooth: true,
                        },
                    ]
                };

                this.chartsIns.setOption(option, true);
            },
        },
        mounted: function() {
            var me = this;
            this.recvtime = [];
            this.speeds = [];
            this.distances = [];
            this.totalad = [];
            this.idleArr = [];
            this.devStates = [];
            this.devStates = [];
            this.voltages = [];
            this.chartsIns = echarts.init(document.getElementById('idle-charts'));
            this.charts();
            this.records = [];
            this.initMap();
            this.queryDevicesTree();
            window.onresize = function() {
                me.chartsIns.resize();
            }
        }
    });

}



function idleOilReport(groupslist) {

    vueInstanse = new Vue({
        el: "#idle-oil-report",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            isSpin: false,
            markerModal: false,
            marker: '',
            tank: '0',
            intervalminutes: '5',
            activeTab: 'tabTotal',
            groupslist: [],
            allColumns: [{
                    title: vRoot.$t("reportForm.index"),
                    key: 'index',
                    width: 70,
                }, {
                    title: vRoot.$t("alarm.action"),
                    width: 80,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    vueInstanse.getDetailTableData(params.row.deviceid, params.row);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.detailed") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid'
                },
                {
                    title: vRoot.$t("monitor.groupName"),
                    key: 'groupname',
                    width: 100,
                },
                {
                    title: vRoot.$t("reportForm.selectTime"),
                    key: 'dateStr',
                },
                { title: vRoot.$t("reportForm.fuelVolume") + '(L)', key: 'addOil', width: 120, sortable: true },
                { title: vRoot.$t("reportForm.oilLeakage") + '(L)', key: 'leakOil', width: 120, sortable: true },
                {
                    title: vRoot.$t("reportForm.idleoil") + '(L)',
                    key: 'usedFuel',
                    sortable: true,
                    width: 120,
                },
                { title: isZh ? '怠速时长' : 'Duration', key: 'durationStr', width: 110 },
                {
                    title: vRoot.$t("reportForm.idleTimes"),
                    key: 'count',
                    width: 100,
                },
            ],
            allTableData: [],
            columns: [
                { title: vRoot.$t('reportForm.index'), key: 'index', width: 70 },
                { title: vRoot.$t('alarm.devName'), key: 'devicename', width: 150 },
                { title: vRoot.$t('reportForm.oilChannel'), key: 'oilindex', width: 80 },
                { title: vRoot.$t('reportForm.idleStartFuel') + '(L)', key: 'soil', width: 120 },
                { title: vRoot.$t('reportForm.idleEndFuel') + '(L)', key: 'eoil', width: 120 },
                { title: vRoot.$t("reportForm.fuelVolume") + '(L)', key: 'addoilinmemory', width: 120, sortable: true },
                { title: vRoot.$t("reportForm.oilLeakage") + '(L)', key: 'leakoilinmemory', width: 120, sortable: true },
                { title: vRoot.$t("reportForm.idleoil") + '(L)', key: 'idleoilinmemory', width: 120, sortable: true },
                { title: isZh ? '怠速时长' : 'Duration', key: 'durationStr', width: 110 },
                { title: vRoot.$t('reportForm.startDate'), width: 160, key: 'begintimeStr', width: 170, },
                { title: vRoot.$t('reportForm.endDate'), width: 160, key: 'endtimeStr', width: 170, },
                {
                    title: vRoot.$t('reportForm.saddress'),
                    width: 540,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.slat ? row.slat.toFixed(5) : null;
                        var lon = row.slon ? row.slon.toFixed(5) : null;
                        if (lat && lon) {
                            if (row.saddress == null) {
                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    row.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('span', {}, row.saddress);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
                {
                    title: vRoot.$t('alarm.action'),
                    width: 100,
                    render: function(h, params) {
                        var row = params.row;
                        return h('div', {}, [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        vueInstanse.queryTracks(row);
                                    }
                                }
                            }, vRoot.$t('reportForm.viewTrack')),
                        ])
                    }
                },
            ],
            tableData: [],
            recvtime: [],
            interval: '100',
            trackDetailModal: false,
        },
        mixins: [treeMixin],
        methods: {
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('idle-details-map');
            },
            queryTracks: function(row) {
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: row.begintimeStr,
                        endtime: row.endtimeStr,
                        interval: 5,
                        timezone: timeDifference
                    };
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.trackDetailModal = true;
                            utils.markersAndLineLayerToMap(me, records);
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            editOilRecord: function() {
                var me = this;
                var url = myUrls.editOilRecord();
                var data = {
                    oilrecordid: editObjectRow.oilrecordid,
                    marker: this.marker,
                    deviceid: editObjectRow.deviceid,
                    oilindex: editObjectRow.oilindex
                };
                utils.sendAjax(url, data, function(resp) {
                    if (resp.status == 0) {
                        me.$Message.success(isZh ? '编辑成功' : 'Edited successfully');
                        editObjectRow.marker = data.marker;
                        me.markerModal = false;
                    } else if (resp.status == 1) {
                        me.$Message.error(isZh ? '正在加油或者漏油中，请稍后备注' : 'Adding or leaking, please marker later');
                    }
                });
            },
            exportData: function() {
                if (this.activeTab == 'tabTotal') {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t("alarm.devNum"),
                            vRoot.$t("monitor.groupName"),
                            vRoot.$t("reportForm.selectTime"),
                            vRoot.$t("reportForm.fuelVolume") + '(L)',
                            vRoot.$t("reportForm.oilLeakage") + '(L)',
                            vRoot.$t("reportForm.idleoil") + '(L)',
                            isZh ? '怠速时长' : 'Duration',
                            isZh ? '怠速时长(H)' : 'Duration(H)',
                            vRoot.$t("reportForm.idleTimes"),
                        ]
                    ];
                    this.allTableData.forEach(function(item, index) {
                        var itemArr = [];
                        itemArr.push(index + 1);
                        itemArr.push(item.devicename);
                        itemArr.push(item.deviceid);
                        itemArr.push(item.groupname);
                        itemArr.push(item.dateStr);
                        itemArr.push(item.addOil);
                        itemArr.push(item.leakOil);
                        itemArr.push(item.usedFuel);
                        itemArr.push(item.durationStr);
                        itemArr.push(item.duration);
                        itemArr.push(item.count);
                        data.push(itemArr);
                    });
                    var options = {
                        title: vRoot.$t('reportForm.idleStatistics'),
                        data: data,
                        dateRange: false,
                    }
                    new XlsxCls(options).exportExcel();
                } else {

                    var data = [
                        [
                            vRoot.$t("reportForm.index"),
                            vRoot.$t("alarm.devName"),
                            vRoot.$t('reportForm.oilChannel'),
                            vRoot.$t('reportForm.idleStartFuel') + '(L)',
                            vRoot.$t('reportForm.idleEndFuel') + '(L)',
                            vRoot.$t("reportForm.fuelVolume") + '(L)',
                            vRoot.$t("reportForm.oilLeakage") + '(L)',
                            vRoot.$t("reportForm.idleoil") + '(L)',
                            isZh ? '怠速时长' : 'Duration',
                            isZh ? '怠速时长(H)' : 'Duration(H)',
                            vRoot.$t('reportForm.startDate'),
                            vRoot.$t('reportForm.endDate'),
                            isZh ? '地址' : 'Address',
                        ]
                    ];
                    var deviceid = ' - ';
                    var len = this.tableData.length - 1;
                    this.tableData.forEach(function(item, index) {
                        var itemArr = [];
                        if (index == 0) {
                            deviceid += item.deviceid;
                        }

                        if (len == index) {

                            itemArr.push(isZh ? '总计' : 'Total');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push(item.idleoilinmemory);
                            itemArr.push(item.durationStr);
                            itemArr.push(item.duration);
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');
                            itemArr.push('');

                        } else {

                            itemArr.push(index + 1);
                            itemArr.push(item.devicename);
                            itemArr.push(item.oilindex);
                            itemArr.push(item.soil);
                            itemArr.push(item.eoil);
                            itemArr.push(item.addoilinmemory);
                            itemArr.push(item.leakoilinmemory);
                            itemArr.push(item.idleoilinmemory);
                            itemArr.push(item.durationStr);
                            itemArr.push(item.durationStr);
                            itemArr.push(item.duration);
                            itemArr.push(item.begintimeStr);
                            itemArr.push(item.endtimeStr);
                            itemArr.push(item.saddress);

                        }

                        data.push(itemArr);
                    });

                    var options = {
                        title: vRoot.$t('reportForm.idleDetailed') + deviceid,
                        data: data,
                    }
                    new XlsxCls(options).exportExcel();


                }

            },

            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 190;
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            getDetailTableData: function(deviceid, row) {
                var records = deepClone(row.records);
                records.sort(function(a, b) {
                    return b.begintime - a.begintime;
                })
                records.forEach(function(record, index) {
                    record.index = index + 1;

                    if (record.slat == 0) {
                        record.slat = record.elat;
                    }
                    if (record.slon == 0) {
                        record.slon = record.elon;
                    }

                    var slat = record.slat.toFixed(5);
                    var slon = record.slon.toFixed(5);
                    var saddress = LocalCacheMgr.getAddress(slon, slat);
                    if (saddress != null) {
                        record.saddress = saddress;
                    } else {
                        record.saddress = null;
                    };



                    record.deviceid = deviceid;
                    record.devicename = vstore.state.deviceInfos[deviceid].devicename;
                    record.begintimeStr = DateFormat.longToLocalDateTimeStr(record.begintime);
                    record.endtimeStr = DateFormat.longToLocalDateTimeStr(record.endtime);
                    record.duration = ((record.endtime - record.begintime) / 1000 / 3600).toFixed(2);;
                    record.durationStr = utils.timeStamp(record.endtime - record.begintime);

                });
                records.push({
                    devicename: isZh ? '总计' : 'Total',
                    idleoilinmemory: row.usedFuel,
                    duration: row.duration,
                    durationStr: row.durationStr,
                    begintimeStr: '',
                    endtimeStr: '',
                })
                this.tableData = records;



                this.queryOiltime(deviceid);
            },
            queryOiltime: function(deviceid) {
                var me = this;
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [deviceid],
                };

                // this.loading = true;
                utils.sendAjax(myUrls.reportOilTime(), data, function(resp) {
                    // me.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {
                            var records = [],
                                totalads = [],
                                voltages = [],
                                speeds = [],
                                distances = [],
                                recvtime = [],
                                idleArr = [],
                                accStates = [],
                                devStates = [];
                            firstDistance = 0;
                            resp.records.forEach(function(item) {
                                records = item.records;
                                records.forEach(function(record, index) {

                                    if (index == 0) {
                                        firstDistance = record.totaldistance;
                                    };

                                    voltages.push(record.voltage / 100);
                                    var totalad = record.totalad;

                                    record.totalad = totalad / 100;

                                    record.speed = (record.speed / 1000).toFixed(2);
                                    record.updatetimeStr = DateFormat.longToLocalDateTimeStr(record.updatetime);
                                    // record.arrivedtimeStr = DateFormat.longToLocalDateTimeStr(record.arrivedtime);
                                    accStates.push(utils.getAccSwitchStatusStr(record));
                                    devStates.push(isZh ? record.strstatus : record.strstatusen);
                                    totalads.push(record.totalad);
                                    speeds.push(record.speed);
                                    record.totaldistance = ((record.totaldistance - firstDistance) / 1000).toFixed(2);
                                    distances.push(record.totaldistance);
                                    recvtime.push(record.updatetimeStr);
                                    var isIdle = me.isIdleTrack(record);
                                    if (isIdle) {
                                        idleArr.push(record.totalad);
                                    } else {
                                        idleArr.push('-');
                                    }

                                });
                            });

                            me.recvtime = recvtime;
                            me.speeds = speeds;
                            me.distances = distances;
                            me.totalad = totalads;
                            me.idleArr = idleArr;
                            me.voltages = voltages;
                            me.devStates = devStates;
                            me.accStates = accStates;
                            me.charts();
                        } else {
                            me.$Message.error(me.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(resp.cause);
                    }
                }, function() {
                    me.loading = false;
                })

            },

            isIdleTrack: function(track) {
                var isIdle = false;
                var status = track.status;
                //0 0：未启用Acc 2:ACC 关；3： ACC 开
                var acc = (status & 0x03);
                if (acc == 0x03) {
                    var speed = track.speed;
                    if (speed <= 0) {
                        isIdle = true;
                    }
                }
                return isIdle;
            },
            onClickQuery: function() {
                var self = this;
                this.activeTab = 'tabTotal';
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });

                if (deviceids.length == 0) {
                    this.$Message.error(this.$t('reportForm.selectDevTip'));
                    return;
                }
                this.tableData = [];
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: deviceids,
                    oilstate: 1,
                    oilindex: Number(self.tank),
                    interval: Number(this.interval),
                    intervalminutes: Number(this.intervalminutes)
                };
                var dateStr = data.startday + ' - ' + data.endday;
                this.loading = true;
                utils.sendAjax(myUrls.reportOilIdle(), data, function(resp) {
                    self.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {

                            resp.records.forEach(function(item, index) {
                                item.index = index + 1;
                                item.dateStr = dateStr;
                                item.devicename = vstore.state.deviceInfos[item.deviceid].devicename;
                                item.groupname = utils.getGroupName(groupslist, item.deviceid);
                                var usedFuel = 0;
                                var addOil = 0;
                                var leakOil = 0;
                                var records = item.records;
                                var duration = 0;
                                records.forEach(function(record) {

                                    record.addoilinmemory = record.addoilinmemory / 100;
                                    record.leakoilinmemory = record.leakoilinmemory / 100;
                                    record.idleoilinmemory = record.idleoilinmemory / 100;

                                    record.eoil = record.eoil / 100;
                                    record.soil = record.soil / 100;

                                    usedFuel += record.idleoilinmemory;
                                    addOil += record.addoilinmemory;
                                    leakOil += record.leakoilinmemory;

                                    duration += (record.endtime - record.begintime);
                                    var lat = record.slat.toFixed(5);
                                    var lon = record.slon.toFixed(5);
                                    var saddress = LocalCacheMgr.getAddress(lon, lat);
                                    if (saddress != null) {
                                        record.saddress = saddress;
                                    } else {
                                        utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                            if (resp && resp.address) {
                                                (function(lon, lat, record, resp) {
                                                    record.saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                })(lon, lat, record, resp)
                                            }
                                        })
                                    };
                                });

                                usedFuel = usedFuel.toFixed(2);
                                item.usedFuel = usedFuel;
                                item.addOil = addOil;
                                item.leakOil = leakOil;
                                item.count = records.length;

                                item.duration = (duration / 1000 / 3600).toFixed(2);;
                                item.durationStr = utils.timeStamp(duration, isZh);

                            });

                            self.allTableData = resp.records;

                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            onSortChange: function(column) {

            },
            charts: function() {
                var totoil = vRoot.$t('reportForm.oil');
                var speed = vRoot.$t('reportForm.speed');
                var dis = vRoot.$t('reportForm.mileage');
                var time = vRoot.$t('reportForm.time');
                var usoil1 = vRoot.$t('reportForm.oil1');
                var usoil2 = vRoot.$t('reportForm.oil2');
                var usoil3 = vRoot.$t('reportForm.oil3');
                var usoil4 = vRoot.$t('reportForm.oil4');
                var status = vRoot.$t('reportForm.status');
                var idle = isZh ? '怠速' : 'Idle';
                var accstates = isZh ? 'Acc状态' : 'Acc State';
                var voltage = isZh ? '电压' : 'Voltage';

                var option = {

                    grid: {
                        top: 30,
                        left: 60,
                        right: 60,
                        bottom: 40,
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';

                            for (i in v) {
                                var seriesName = v[i].seriesName;
                                if (seriesName && seriesName != time) {
                                    if (seriesName == dis) {
                                        var currentDistance = v[i].value;
                                        var totalDistance = ((Number(currentDistance) + firstDistance) / 1000).toFixed(2);
                                        data += seriesName + ' : ' + currentDistance + "(T:" + totalDistance + ")" + 'km<br/>';

                                    } else if (seriesName == totoil || seriesName == idle || seriesName == usoil1 || seriesName == usoil2 || seriesName == usoil3 || seriesName == usoil4) {
                                        if (v[i].value != '-') {
                                            data += seriesName + ' : ' + v[i].value + 'L<br/>';
                                        } else {
                                            data += seriesName + ' : ' + v[i].value + '<br/>';
                                        }
                                    } else if (seriesName == speed) {
                                        data += seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                    } else if (seriesName == voltage) {
                                        data += seriesName + ' : ' + v[i].value + 'V<br/>';
                                    } else {
                                        data += seriesName + ' : ' + v[i].value + '<br/>';
                                    }
                                }
                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [speed, dis, totoil, idle],
                        selected: this.selectedLegend,
                        x: 'left',
                        // width: 600,
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        //fillerColor:'rgb(244,129,38,0.8)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: '', //totoil + '/' + speed
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,

                    }, {
                        name: '', //dis
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,
                        // min: this.disMin,
                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            smooth: true,
                            color: '#4876FF',
                            data: this.speeds
                        }, {
                            name: dis,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            color: '#3CB371',
                            smooth: true,
                            data: this.distances
                        }, {
                            smooth: true,
                            name: totoil,
                            type: 'line',
                            symbol: 'none',
                            color: 'black',
                            data: this.totalad,
                        }, {
                            smooth: true,
                            name: idle,
                            type: 'line',
                            symbol: 'none',
                            color: 'red',
                            data: this.idleArr,
                        },
                        {
                            name: accstates,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.accStates,
                            smooth: true,
                        },
                        {
                            name: voltage,
                            type: 'line',
                            symbol: 'none',
                            color: '#e2e2e2',
                            data: this.voltages,
                            smooth: true,
                        },
                        {
                            name: status,
                            type: 'line',
                            symbol: 'none',
                            color: '#000',
                            data: this.devStates,
                            smooth: true,
                        },
                    ]
                };

                this.chartsIns.setOption(option, true);
            },
        },
        mounted: function() {
            var me = this;
            this.recvtime = [];
            this.speeds = [];
            this.distances = [];
            this.totalad = [];
            this.idleArr = [];
            this.voltages = [];
            this.accStates = [];
            this.devStates = [];
            this.chartsIns = echarts.init(document.getElementById('idle-charts'));
            this.charts();
            this.records = [];
            this.initMap();
            this.queryDevicesTree();
            window.onresize = function() {
                me.chartsIns.resize();
            }
        }
    });

}



function temperature(groupslist) {
    vueInstanse = new Vue({
        el: "#temperature",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            groupslist: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), type: 'index', width: 70 },
                { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 110 },
                { title: vRoot.$t("reportForm.time"), key: 'updatetimeStr', sortable: true, width: 150 },
                { title: vRoot.$t("reportForm.speed"), key: 'speed', width: 80 },
                { title: vRoot.$t("reportForm.temp1"), key: 'temp1', width: 80 },
                { title: vRoot.$t("reportForm.temp2"), key: 'temp2', width: 80 },
                { title: vRoot.$t("reportForm.temp3"), key: 'temp3', width: 80 },
                { title: vRoot.$t("reportForm.temp4"), key: 'temp4', width: 80 },
                { title: vRoot.$t("reportForm.averageTemp"), key: 'averageTemp', width: 90 },
                { title: vRoot.$t("reportForm.humi"), key: 'humi1', width: 90 },
                { title: vRoot.$t("reportForm.status"), key: 'strstatus' },
                {
                    title: vRoot.$t("reportForm.lon") + ',' + vRoot.$t("reportForm.lat"),
                    render: function(h, params) {
                        var row = params.row;
                        var callat = row.callat.toFixed(5);
                        var callon = row.callon.toFixed(5);

                        if (callat && callon) {
                            if (row.address == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(callon, callat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.tableData[params.index].address = resp.address;
                                                    LocalCacheMgr.setAddress(callon, callat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, callon + "," + callat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.address,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, callon + "," + callat)
                                ]);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                },
            ],
            tableData: [],
            recvtime: [],
            veo: [],
            temp1: [],
            temp2: [],
            temp3: [],
            temp4: [],
            averageTemp: [],
            humi1s: [],
            currentIndex: 1,
        },
        mixins: [reportMixin],
        methods: {
            exportData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.time"),
                        vRoot.$t("reportForm.speed"),
                        vRoot.$t("reportForm.temp1"),
                        vRoot.$t("reportForm.temp2"),
                        vRoot.$t("reportForm.temp3"),
                        vRoot.$t("reportForm.temp4"),
                        vRoot.$t("reportForm.averageTemp"),
                        vRoot.$t("reportForm.humi"),
                        vRoot.$t("reportForm.status"),
                        vRoot.$t("reportForm.lon") + ',' + vRoot.$t("reportForm.lat"),
                    ]
                ];
                this.tableData.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.updatetimeStr);
                    itemArr.push(item.speed);
                    itemArr.push(item.temp1);
                    itemArr.push(item.temp2);
                    itemArr.push(item.temp3);
                    itemArr.push(item.temp4);
                    itemArr.push(item.averageTemp);
                    itemArr.push(item.humi1);
                    itemArr.push(item.strstatus);

                    var callat = item.callat.toFixed(5);
                    var callon = item.callon.toFixed(5);
                    itemArr.push(callon + ',' + callat);

                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.temperatureChart'),
                    data: data,
                }
                new XlsxCls(options).exportExcel();

            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentPageIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            charts: function() {
                var speed = vRoot.$t("reportForm.speed");
                var time = vRoot.$t("reportForm.time");
                var temp = vRoot.$t("reportForm.temp");
                var temp1 = vRoot.$t("reportForm.temp1");
                var temp2 = vRoot.$t("reportForm.temp2");
                var temp3 = vRoot.$t("reportForm.temp3");
                var temp4 = vRoot.$t("reportForm.temp4");
                var averageTemp = vRoot.$t("reportForm.averageTemp");
                var humi1 = vRoot.$t("reportForm.humi");
                var option = {
                    title: {
                        text: speed + '/' + temp,
                        x: 'center',
                        textStyle: {
                            fontSize: 12,
                            fontWeight: 'bolder',
                            color: '#333'
                        }
                    },
                    grid: {
                        x: 50,
                        y: 40,
                        x2: 50,
                        y2: 40
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(v) {
                            var data = time + ' : ' + v[0].name + '<br/>';
                            for (i in v) {
                                if (v[i].seriesName) {
                                    if (v[i].seriesName != time) {
                                        if (v[i].seriesName == speed) {
                                            data += v[i].seriesName + ' : ' + v[i].value + 'km/h<br/>';
                                        } else {
                                            data += v[i].seriesName + ' : ' + v[i].value + '<br/>';
                                        }
                                    }
                                }

                            }
                            return data;
                        },
                        position: utils.toolTipPosition,
                    },
                    legend: {
                        data: [temp1, temp2, temp3, temp4, averageTemp, humi1, speed],
                        x: 'left',
                        selected: this.selectedLegend,
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: {
                                show: true
                            }
                        },
                        itemSize: 14
                    },
                    dataZoom: [{
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        backgroundColor: '#EDEDED',
                        fillerColor: 'rgb(54, 72, 96,0.5)',
                        bottom: 0
                    }, {
                        type: "inside",
                        realtime: true,
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 0
                    }],
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            onZero: false
                        },
                        data: this.recvtime
                    }],
                    yAxis: [{
                        name: temp,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 5,
                        axisLabel: {
                            formatter: '{value}℃',
                        },

                    }, {
                        name: speed,
                        type: 'value',
                        nameTextStyle: 10,
                        nameGap: 2,

                        axisLabel: {
                            formatter: '{value} km',
                        },
                        axisTick: {
                            show: false
                        }
                    }],
                    series: [{
                            name: time,
                            type: 'line',
                            symbol: 'none',
                            xAxisIndex: 0,
                            color: '#F0805A',
                            smooth: true,
                            data: this.recvtime
                        }, {
                            name: speed,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 1,
                            smooth: true,
                            color: '#4876FF',
                            data: this.veo,
                        }, {
                            smooth: true,
                            name: temp1,
                            type: 'line',
                            symbol: 'none',
                            color: '#C1232B',
                            data: this.temp1,
                            yAxisIndex: 0,
                        }, {
                            //show:'false',
                            name: temp2,
                            type: 'line',
                            symbol: 'none',
                            color: '#8E388E',
                            data: this.temp2,
                            yAxisIndex: 0,
                            smooth: true,
                        },

                        {
                            smooth: true,
                            name: temp3,
                            type: 'line',
                            symbol: 'none',
                            color: '#FF4500',
                            data: this.temp3,
                            yAxisIndex: 0,
                        },
                        {
                            smooth: true,
                            name: temp4,
                            type: 'line',
                            symbol: 'none',
                            color: '#e4393c',
                            yAxisIndex: 0,
                            data: this.temp4
                        },
                        {
                            name: averageTemp,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#3CB371',
                            smooth: true,
                            data: this.averageTemp
                        },
                        {
                            name: humi1,
                            type: 'line',
                            symbol: 'none',
                            yAxisIndex: 0,
                            color: '#9EEA6A',
                            smooth: true,
                            data: this.humi1s
                        },
                    ]
                };

                this.chartsIns.setOption(option, true);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 400;
            },
            onClickQuery: function() {
                if (this.queryDeviceId == "") { return };
                var self = this;
                if (this.isSelectAll === null) {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                    return;
                };
                var data = {
                    // username: vstore.state.userName,
                    startday: this.dateVal[0],
                    endday: this.dateVal[1],
                    offset: timeDifference,
                    devices: [this.queryDeviceId],
                };
                this.loading = true;
                utils.sendAjax(myUrls.reportTempTime(), data, function(resp) {
                    self.loading = false;
                    if (resp.status == 0) {
                        if (resp.records) {
                            var records = [],
                                veo = [],
                                recvtime = [],
                                temp1 = [],
                                temp2 = [],
                                temp3 = [],
                                temp4 = [],
                                humi1s = [],
                                averageTemp = [];
                            resp.records.forEach(function(item, index) {
                                records = item.records;
                                var independent = item.independent === 0;
                                records.forEach(function(record) {
                                    var averageT = 0;
                                    var averageCount = 0;
                                    var callon = record.callon.toFixed(5);
                                    var callat = record.callat.toFixed(5);
                                    var address = LocalCacheMgr.getAddress(callon, callat);

                                    if (address != null) {
                                        record.address = address;
                                    } else {
                                        record.address = null;
                                    }

                                    record.updatetimeStr = DateFormat.longToLocalDateTimeStr(record.updatetime);
                                    record.devicename = vstore.state.deviceInfos[self.queryDeviceId].devicename;

                                    if (record.temp1 != 0xffff && (record.temp1 != 0x1FFFFFFF)) {
                                        record.temp1 = record.temp1 / 100
                                        averageT += record.temp1;
                                        averageCount++;
                                    } else {
                                        record.temp1 = '-';
                                    }
                                    if (record.temp2 != 0xffff && (record.temp2 != 0x1FFFFFFF)) {
                                        record.temp2 = record.temp2 / 100
                                        averageT += record.temp2;
                                        averageCount++;
                                    } else {
                                        record.temp2 = '-';
                                    }
                                    if (record.temp3 != 0xffff && (record.temp3 != 0x1FFFFFFF)) {
                                        record.temp3 = record.temp3 / 100
                                        averageT += record.temp3;
                                        averageCount++;
                                    } else {
                                        record.temp3 = '-';
                                    }
                                    if (record.temp4 != 0xffff && (record.temp4 != 0x1FFFFFFF)) {
                                        record.temp4 = record.temp4 / 100
                                        averageT += record.temp4;
                                        averageCount++;
                                    } else {
                                        record.temp4 = '-';
                                    }
                                    if (record.humi1 > 0) {
                                        record.humi1 = (record.humi1 / 10).toFixed(1);
                                        humi1s.push(record.humi1)
                                    } else {
                                        record.humi1 = '-';
                                        humi1s.push(record.humi1);
                                    }

                                    veo.push((record.speed / 1000).toFixed(2));
                                    temp1.push(record.temp1)
                                    temp2.push(record.temp2)
                                    temp3.push(record.temp3)
                                    temp4.push(record.temp4)
                                    if (averageCount == 0) {
                                        averageTemp.push('-');
                                        record.averageTemp = '-';
                                    } else {
                                        var temp = (averageT / averageCount).toFixed(1);
                                        record.averageTemp = temp;
                                        averageTemp.push(temp);
                                    }
                                    recvtime.push(record.updatetimeStr);

                                });
                            });

                            self.veo = veo;
                            self.recvtime = recvtime;
                            self.temp1 = temp1;
                            self.temp2 = temp2;
                            self.temp3 = temp3;
                            self.temp4 = temp4;
                            self.humi1s = humi1s;
                            self.averageTemp = averageTemp;
                            self.records = records;
                            self.total = records.length;
                            records.sort(function(a, b) {
                                return b.updatetime - a.updatetime;
                            })
                            self.currentPageIndex = 1;
                            self.tableData = records.slice(0, 20);
                            self.charts();
                        } else {
                            self.$Message.error(self.$t("reportForm.noRecord"));
                        }
                    } else {
                        self.$Message.error(resp.cause);
                    }
                })
            },
            onSortChange: function(column) {

            },
            changeTableColumns(selectedLegend) {
                // var temp = vRoot.$t("reportForm.temp");
                var temp1 = vRoot.$t("reportForm.temp1");
                var temp2 = vRoot.$t("reportForm.temp2");
                var temp3 = vRoot.$t("reportForm.temp3");
                var temp4 = vRoot.$t("reportForm.temp4");
                var averageTemp = vRoot.$t("reportForm.averageTemp");
                var humi1 = vRoot.$t("reportForm.humi");

                var columns = [
                    { title: vRoot.$t("reportForm.index"), type: 'index', width: 70 },
                    { title: vRoot.$t("alarm.devName"), key: 'devicename', width: 110 },
                    { title: vRoot.$t("reportForm.time"), key: 'updatetimeStr', sortable: true, width: 150 },
                    { title: vRoot.$t("reportForm.speed"), key: 'speed', width: 80 },
                ];
                if (selectedLegend[temp1]) {
                    columns.push({ title: temp1, key: 'temp1', width: 80 });
                }
                if (selectedLegend[temp2]) {
                    columns.push({ title: temp2, key: 'temp2', width: 80 });
                }
                if (selectedLegend[temp3]) {
                    columns.push({ title: temp3, key: 'temp3', width: 80 });
                }
                if (selectedLegend[temp4]) {
                    columns.push({ title: temp4, key: 'temp4', width: 80 });
                }
                if (selectedLegend[averageTemp]) {
                    columns.push({ title: averageTemp, key: 'averageTemp', width: 90 });
                }
                if (selectedLegend[humi1]) {
                    columns.push({ title: humi1, key: 'humi1', width: 90 });
                }

                columns.push({ title: vRoot.$t("reportForm.status"), key: 'strstatus' });
                columns.push({
                    title: vRoot.$t("reportForm.lon") + ',' + vRoot.$t("reportForm.lat"),
                    render: function(h, params) {
                        var row = params.row;
                        var callat = row.callat.toFixed(5);
                        var callon = row.callon.toFixed(5);

                        if (callat && callon) {
                            if (row.address == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(callon, callat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.tableData[params.index].address = resp.address;
                                                    LocalCacheMgr.setAddress(callon, callat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, callon + "," + callat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.address,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, callon + "," + callat)
                                ]);
                            }
                        } else {
                            return h('span', {}, '');
                        }
                    },
                });
                this.columns = columns;
            }
        },
        mounted: function() {
            var me = this;
            this.groupslist = groupslist;
            this.myChart = null;
            this.records = [];
            if (isZh) {
                this.selectedLegend = {
                    '温度1': true,
                    '温度2': true,
                    '温度3': true,
                    '温度4': true,
                    '平均温度': true,
                    '湿度': true,
                }
            } else {
                this.selectedLegend = {
                    'temp1': true,
                    'temp2': true,
                    'temp3': true,
                    'temp4': true,
                    'Average Temperature': true,
                    'humi': true,
                }
            }

            this.chartsIns = echarts.init(document.getElementById('charts'));
            this.chartsIns.on('legendselectchanged', (param) => {
                me.selectedLegend = param.selected;
                me.changeTableColumns(param.selected);
            })
            this.charts();

        }
    });
}


function driverWorkDetails() {
    vueInstanse = new Vue({
        el: '#driver-work-details',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            columns: [
                { key: 'index', width: 70, title: vRoot.$t("reportForm.index") },
                { title: vRoot.$t("alarm.devName"), key: 'devicename' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid' },
                { title: vRoot.$t("reportForm.drivername"), key: 'drivername' },
                { title: vRoot.$t("reportForm.cardinsertTime"), key: 'uptimeStr', width: 150, },
                {
                    title: vRoot.$t("reportForm.cardinsertAddress"),
                    width: 145,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.uplat;
                        var lon = row.uplon;
                        if (lat && lon) {
                            if (row.saddress == null) {

                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.records[params.index].saddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.saddress,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, lon + "," + lat)
                                ]);
                            }
                        } else {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                    },
                },
                {
                    title: vRoot.$t("reportForm.cardPullTime"),
                    width: 150,
                    key: 'downtimeStr',
                },
                {
                    title: vRoot.$t("reportForm.cardPullAddress"),
                    width: 145,
                    render: function(h, params) {
                        var row = params.row;
                        var lat = row.downlat;
                        var lon = row.downlon;
                        if (lat != '0.00000' && lon != '0.00000') {
                            if (row.eaddress == null) {
                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function() {
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    vueInstanse.records[params.index].eaddress = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('Tooltip', {
                                    props: {
                                        content: row.eaddress,
                                        placement: "top-start",
                                        maxWidth: 200
                                    },
                                }, [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    }, lon + "," + lat)
                                ]);
                            }
                        } else {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                    },
                },
                {
                    title: vRoot.$t("reportForm.workingHours") + '(H)',
                    key: 'workingHours',
                },
                {
                    title: vRoot.$t("reportForm.mileage") + '(km)',
                    key: 'mileage',
                },
                { title: vRoot.$t("reportForm.certificationcode"), key: 'certificationcode' },
                {
                    title: vRoot.$t("alarm.action"),
                    render: function(h, parmas) {
                        var viewTrack = vRoot.$t("reportForm.viewTrack");
                        return h(
                            'Button', {
                                on: {
                                    click: function() {
                                        vueInstanse.queryTracks(parmas.row);
                                    }
                                },
                                props: {
                                    size: 'small',
                                    type: 'info'
                                }
                            },
                            viewTrack
                        )
                    },
                },
            ],
            tableData: [],
            currentIndex: 1,
            trackDetailModal: false,
            deviceName: '',
        },
        methods: {
            queryAllAddress: function() {
                var records = this.records;
                records.forEach(function(item) {
                    if (item.saddress == null) {
                        var uplat = Number(item.uplat);
                        var uplon = Number(item.uplon);
                        if (uplat && uplon) {
                            utils.getJiuHuAddressSyn(uplon, uplat, function(resp) {
                                if (resp && resp.address) {
                                    item.saddress = resp.address;
                                    LocalCacheMgr.setAddress(uplon, uplat, resp.address);
                                }
                            })
                        }
                    }
                    if (item.eaddress == null) {
                        var downlat = Number(item.downlat);
                        var downlon = Number(item.downlon);
                        if (downlat && downlon) {
                            utils.getJiuHuAddressSyn(downlon, downlat, function(resp) {
                                if (resp && resp.address) {
                                    item.eaddress = resp.address;
                                    LocalCacheMgr.setAddress(downlon, downlat, resp.address);
                                }
                            })
                        }
                    }
                });

                this.$Message.success(this.$t('monitor.querySucc'));
            },
            exportTableData: function() {

                var records = deepClone(this.records);
                records.forEach(function(item) {
                    if (item.saddress == null) {
                        item.saddress = item.uplat + "," + item.uplon;
                    }
                    if (item.eaddress == null) {
                        item.eaddress = '';
                    }
                });

                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("reportForm.drivername"),
                        vRoot.$t("reportForm.cardinsertTime"),
                        vRoot.$t("reportForm.cardinsertAddress"),
                        vRoot.$t("reportForm.cardPullTime"),
                        vRoot.$t("reportForm.cardPullAddress"),
                        vRoot.$t("reportForm.workingHours") + '(H)',
                        vRoot.$t("reportForm.mileage") + '(km)',
                        vRoot.$t("reportForm.certificationcode"),
                    ]
                ];

                records.forEach(function(item, index) {
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.drivername);
                    itemArr.push(item.uptimeStr);
                    itemArr.push(item.saddress);
                    itemArr.push(item.downtimeStr);
                    itemArr.push(item.eaddress);
                    itemArr.push(item.workingHours);
                    itemArr.push(item.mileage);
                    itemArr.push(item.certificationcode);
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t("reportForm.driverWorkDetails"),
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();

            },
            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('work-details-map');
            },
            queryTracks: function(row) {
                // this.mapInstance.clearOverlays();
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: row.uptimeStr,
                        endtime: row.downtimeStr,
                        interval: 60,
                        timezone: timeDifference
                    };
                if (row.downtime <= 0) {
                    data.endtime = DateFormat.longToLocalDateTimeStr(row.uptime + 60000)
                }
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;
                        if (records && records.length) {
                            me.trackDetailModal = true;
                            utils.markersAndLineLayerToMap(me, records);
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            setViewPortCenter: function(lines) {
                var me = this;
                setTimeout(function() {
                    var view = me.mapInstance.getViewport(eval(lines));
                    var mapZoom = view.zoom;
                    var centerPoint = view.center;
                    me.mapInstance.centerAndZoom(centerPoint, mapZoom);
                }, 300)
            },
            getBdPoints: function(records) {
                var points = [];
                records.forEach(function(item) {
                    var lon_lat = wgs84tobd09(item.callon, item.callat);
                    points.push(new BMap.Point(lon_lat[0], lon_lat[1]));
                });
                return points;
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 210;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportDriverRecords();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                        me.loading = false;
                        if (resp.status === 0) {
                            if (resp.records.length) {
                                var records = [],
                                    index = 1;
                                resp.records.forEach(function(item) {
                                    item.records.forEach(function(item) {
                                        item.index = index;
                                        var callat = item.uplat = item.uplat.toFixed(5);
                                        var callon = item.uplon = item.uplon.toFixed(5);
                                        var saddress = LocalCacheMgr.getAddress(callon, callat);
                                        if (saddress != null) {
                                            item.saddress = saddress;
                                        } else {
                                            item.saddress = null;
                                        };
                                        var elat = item.downlat = item.downlat.toFixed(5);
                                        var elon = item.downlon = item.downlon.toFixed(5);
                                        var eaddress = LocalCacheMgr.getAddress(elon, elat);
                                        if (eaddress != null) {
                                            item.eaddress = eaddress;
                                        } else {
                                            item.eaddress = null;
                                        };
                                        item.devicename = vstore.state.deviceInfos[item.deviceid] ? vstore.state.deviceInfos[item.deviceid].devicename : item.deviceid;
                                        item.uptimeStr = DateFormat.longToLocalDateTimeStr(item.uptime);
                                        item.downtimeStr = item.downtime == 0 ? '无' : DateFormat.longToLocalDateTimeStr(item.downtime);
                                        item.workingHours = item.downtime == 0 ? '无' : ((item.downtime - item.uptime) / 1000 / 3600).toFixed(2);
                                        item.mileage = item.downdistance == 0 ? '无' : ((item.downdistance - item.updistance) / 1000).toFixed(2);
                                        if (!item.certificationcode) {
                                            item.certificationcode = '无';
                                        }
                                        records.push(item);
                                        index++;

                                    })
                                });
                                me.records = records.sort(function(a, b) { return b.uptime - a.uptime });
                                me.tableData = records.slice(0, 20);
                                me.total = me.records.length;

                            } else {
                                me.tableData = [];
                                me.total = 1;
                                me.records = [];
                            };
                            me.currentIndex = 1;
                        } else {
                            me.tableData = [];
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            me.records = [];
            me.initMap();
            this.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}


function ioReport(groupslist) {
    vueInstanse = new Vue({
        el: '#io-record',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            isSpin: false,
            activeTab: 'tabTotal',
            ioType: [1, 2, 3, 4],
            mapModal: false,
            mapType: utils.getMapType(),
            mapInstance: null,
            markerIns: null,
            loading: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            allIoColumns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 160,
                    render: function(h, params) {
                        return h('span', {
                            on: {
                                click: function() {
                                    vueInstanse.activeTab = "tabDetail";
                                    editObject = params.row;
                                    vueInstanse.getIoDetailTableData(params.row.records);
                                }
                            },
                            style: {
                                color: '#e4393c',
                                cursor: 'pointer'
                            }
                        }, "[" + vRoot.$t("reportForm.ioDetailed") + "]")
                    }
                },
                {
                    title: vRoot.$t("alarm.devName"),
                    key: 'devicename'
                },
                {
                    title: vRoot.$t("alarm.devNum"),
                    key: 'deviceid',
                },
                {
                    title: vRoot.$t("reportForm.ioIndex"),
                    key: 'ioindex',
                },
                { title: vRoot.$t("reportForm.ioname"), key: 'ioname', width: 100 },
                {
                    title: vRoot.$t("reportForm.openCount"),
                    key: 'opennumber',
                },
                {
                    title: vRoot.$t("reportForm.openDuration"),
                    key: 'duration'
                }
            ],
            allIoTableData: [],
            columns: [
                { title: vRoot.$t("reportForm.index"), width: 70, key: 'index' },
                { title: vRoot.$t("alarm.devName"), key: 'deviceName', width: 100 },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid', width: 120 },
                { title: vRoot.$t("reportForm.ioIndex"), key: 'ioindex', width: 100 },
                { title: vRoot.$t("reportForm.ioname"), key: 'ioname', width: 100 },
                { title: vRoot.$t("reportForm.startDate"), key: 'startDate', width: 150 },
                { title: vRoot.$t("reportForm.endDate"), key: 'endDate', width: 150 },
                { title: vRoot.$t("reportForm.minMileage") + "(km)", key: 'sdistance' },
                { title: vRoot.$t("reportForm.maxMileage") + "(km)", key: 'edistance' },
                { title: vRoot.$t("reportForm.duration") + '(H)', key: 'duration' },
                {
                    title: isZh ? '地图' : 'Map',
                    width: 125,
                    render: function(h, params) {
                        var row = params.row;
                        if (row.elat) {
                            return h(
                                'Button', {
                                    on: {
                                        click: function() {
                                            vueInstanse.queryTracks(row);
                                        }
                                    }
                                },
                                '查看地图');
                        } else {
                            return h('span', {}, '');
                        }
                    }
                },
            ],
            tableData: [],
        },
        methods: {
            getBdPoints: function(records) {
                var points = [];
                records.forEach(function(item) {
                    var lon_lat = wgs84tobd09(item.callon, item.callat);
                    points.push(new BMap.Point(lon_lat[0], lon_lat[1]));
                });
                return points;
            },
            queryTracks: function(row) {
                var url = myUrls.queryTracks(),
                    me = this,
                    data = {
                        deviceid: row.deviceid,
                        begintime: row.startDate,
                        endtime: row.endDate,
                        interval: 5,
                        timezone: timeDifference
                    };
                if (row.downtime <= 0) {
                    data.endtime = DateFormat.longToLocalDateTimeStr(row.uptime + 60000)
                }
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        var records = respData.records;

                        if (records && records.length > 0) {
                            utils.markersAndLineLayerToMap(me, records)
                            me.mapModal = true;
                        } else {
                            me.$Message.error(vRoot.$t("reportForm.noRecord"));
                        }
                    } else {
                        me.$Message.error(vRoot.$t("reportForm.queryFail"));
                    }

                });
            },
            getLineFeature: function(tracksList) {
                var arrayList = [];
                tracksList.forEach(function(track) {
                    arrayList.push(ol.proj.fromLonLat([track.callon, track.callat]));
                });
                return new ol.Feature(new ol.geom.LineString(arrayList));
            },
            setViewPortCenter: function(lines) {
                var me = this;
                setTimeout(function() {
                    var view = me.mapInstance.getViewport(eval(lines));
                    var mapZoom = view.zoom;
                    var centerPoint = view.center;
                    me.mapInstance.centerAndZoom(centerPoint, mapZoom);
                }, 300)
            },
            getFirstMarkerIcon: function(isStart) {
                var iconName = isStart ? 'marker_qidian.png' : 'marker_zhongdian.png';
                var pathname = location.pathname
                var imgPath = '';
                if (utils.isLocalhost()) {
                    imgPath = myUrls.viewhost + 'images/map/' + iconName;
                } else {
                    imgPath = '../images/map/' + iconName;
                };
                if (utils.getMapType() == 'bMap') {
                    return new BMap.Icon("./images/map/" + iconName, new BMap.Size(32, 32), {
                        imageOffset: new BMap.Size(0, 0)
                    });
                } else if (utils.getMapType() == 'gMap') {
                    return imgPath;
                } else {
                    return new ol.style.Style({
                        image: new ol.style.Icon(({
                            crossOrigin: 'anonymous',
                            src: imgPath,
                            rotation: 0, //角度转化为弧度
                            imgSize: [32, 32]
                        }))
                    });
                }
            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('posi-map');
            },
            onIoChange: function(list) {
                this.ioType = list;
            },
            exportData: function() {

                if (this.activeTab == "tabTotal") {
                    if (this.allIoTableData.length) {
                        var data = [
                            [
                                vRoot.$t("reportForm.index"),
                                vRoot.$t("alarm.devName"),
                                vRoot.$t("alarm.devNum"),
                                vRoot.$t("reportForm.ioIndex"),
                                vRoot.$t("reportForm.ioname"),
                                vRoot.$t("reportForm.openCount"),
                                vRoot.$t("reportForm.openDuration"),
                            ]
                        ];
                        this.allIoTableData.forEach(function(item, index) {
                            var itemArr = [];
                            itemArr.push(index + 1);
                            itemArr.push(item.devicename);
                            itemArr.push(item.deviceid);
                            itemArr.push(item.ioindex);
                            itemArr.push(item.ioname);
                            itemArr.push(item.opennumber);
                            itemArr.push(item.duration);
                            data.push(itemArr);
                        });
                        var options = {
                            title: isZh ? "IO统计" : "io-total",
                            data: data,
                            dateRange: this.queryDateRange,
                        }
                        new XlsxCls(options).exportExcel();
                    }
                } else {
                    if (this.tableData.length) {



                        var data = [
                            [
                                vRoot.$t("reportForm.index"),
                                vRoot.$t("alarm.devName"),
                                vRoot.$t("alarm.devNum"),
                                vRoot.$t("reportForm.ioIndex"),
                                vRoot.$t("reportForm.ioname"),
                                vRoot.$t("reportForm.startDate"),
                                vRoot.$t("reportForm.endDate"),
                                vRoot.$t("reportForm.minMileage") + "(km)",
                                vRoot.$t("reportForm.maxMileage") + "(km)",
                                vRoot.$t("reportForm.openDuration"),
                            ]
                        ];

                        var len = this.tableData.length - 1;

                        this.tableData.forEach(function(item, index) {
                            console.log(item);
                            var itemArr = [];
                            itemArr.push(index + 1);
                            if (len == index) {
                                itemArr.push('');
                                itemArr.push('');
                                itemArr.push('');
                                itemArr.push('');
                                itemArr.push('');
                                itemArr.push('');
                                itemArr.push('');
                                itemArr.push('');
                                itemArr.push(item.duration);
                            } else {
                                itemArr.push(item.deviceName);
                                itemArr.push(item.deviceid);
                                itemArr.push(item.ioindex);
                                itemArr.push(item.ioname);
                                itemArr.push(item.startDate);
                                itemArr.push(item.endDate);
                                itemArr.push(item.sdistance);
                                itemArr.push(item.edistance);
                                itemArr.push(item.duration);
                            }

                            data.push(itemArr);
                        });

                        var options = {
                            title: (isZh ? "IO详情" : "io-details") + ' - ' + editObject.deviceid,
                            data: data,
                            dateRange: this.queryDateRange,
                        }
                        new XlsxCls(options).exportExcel();

                    }
                }
            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            onClickTab: function(name) {
                this.activeTab = name;
            },
            onChange: function(value) {
                this.dateVal = value;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 220;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length) {
                    var me = this;
                    var url = myUrls.reportIoStates();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids,
                        ioindexs: this.ioType.map(function(item) { return Number(item) })
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                        if (resp.status == 0) {
                            if (resp.records && resp.records.length) {
                                me.tableData = [];
                                me.allIoTableData = me.getAllIoTableData(resp.records);
                            } else {
                                me.tableData = [];
                                me.allIoTableData = [];
                                me.$Message.error(me.$t("reportForm.noRecord"));
                            }
                        } else {
                            me.tableData = [];
                            me.allIoTableData = [];
                        }
                        if (me.activeTab != "tabTotal") {
                            me.onClickTab("tabTotal");
                        }
                    });
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            getAllIoTableData: function(records) {
                var allIoTableData = [],
                    me = this;
                records.forEach(function(item, index) {
                    var ioname = '';
                    var opennumber = 0;
                    var accObj = {
                            index: index + 1,
                            deviceid: "\t" + item.deviceid,
                            opennumber: 0,
                            duration: "",
                            devicename: vstore.state.deviceInfos[item.deviceid].devicename,
                            records: item.records,
                            ioindex: item.ioindex,
                        },
                        duration = 0;
                    item.records.forEach(function(device) {
                        if (device.iostate == 1) {
                            duration += (device.endtime - device.begintime);
                            ioname = device.ioname;
                            opennumber++;
                        }
                    });
                    accObj.ioname = ioname;
                    accObj.opennumber = opennumber;
                    accObj.duration = (duration / 1000 / 3600).toFixed(2);;
                    allIoTableData.push(accObj);
                });
                return allIoTableData;
            },
            getIoDetailTableData: function(records) {
                var newRecords = [],
                    me = this;
                var ioOpenTime = 0;
                var ioCloseTime = 0;
                var openName = '';
                var closeName = '';
                records.sort(function(a, b) {
                    return a.begintime - b.begintime;
                });
                records.forEach(function(item, index) {
                    var deviceName = vstore.state.deviceInfos[item.deviceid].devicename;
                    var duration = item.endtime - item.begintime;
                    var durationStr = (duration / 1000 / 3600).toFixed(2);;
                    if (item.iostate == 1) {
                        openName = item.ioname;
                        ioOpenTime += duration;
                    } else {
                        closeName = item.ioname;
                        ioCloseTime += duration;
                    }
                    newRecords.push({
                        index: index + 1,
                        ioindex: item.ioindex,
                        deviceid: item.deviceid,
                        deviceName: deviceName,
                        startDate: DateFormat.longToLocalDateTimeStr(item.begintime),
                        endDate: DateFormat.longToLocalDateTimeStr(item.endtime),
                        sdistance: (item.sdistance / 1000).toFixed(2),
                        edistance: (item.edistance / 1000).toFixed(2),
                        ioname: item.ioname,
                        duration: durationStr,
                        slon: item.slon,
                        slat: item.slat,
                        elon: item.elon,
                        elat: item.elat,
                        iostate: item.iostate
                    });
                });
                newRecords.push({
                    duration: openName + ':' + (ioOpenTime / 1000 / 3600).toFixed(2) + "," + closeName + ":" + (ioCloseTime / 1000 / 3600).toFixed(2)
                })
                me.tableData = newRecords;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
        },
        mounted: function() {
            var me = this;
            this.queryDevicesTree();
            this.calcTableHeight();
            this.initMap();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })

}


function multiMedia() {
    vueInstanse = new Vue({
        el: '#multi-media',
        i18n: utils.getI18n(),
        mixins: [treeMixin],
        data: {
            loading: false,
            isSpin: false,
            dateVal: [DateFormat.longToDateStr(Date.now(), timeDifference), DateFormat.longToDateStr(Date.now(), timeDifference)],
            lastTableHeight: 100,
            groupslist: [],
            timeoutIns: null,
            columns: [
                { key: 'index', width: 70, title: vRoot.$t("reportForm.index") },
                { title: vRoot.$t("alarm.devName"), key: 'devicename' },
                { title: vRoot.$t("alarm.devNum"), key: 'deviceid' },
                {
                    title: vRoot.$t("alarm.fileType"),
                    key: 'fileext',
                    width: 100,
                },
                {
                    title: vRoot.$t("monitor.channel"),
                    key: 'channelid',
                    width: 80,
                },
                {
                    title: vRoot.$t("alarm.alarmType"),
                    key: 'eventcodeStr',
                    width: 150,
                },
                {
                    title: vRoot.$t("alarm.receivingTime"),
                    key: 'endtimeStr',
                    width: 150,
                },
                {
                    title: vRoot.$t("reportForm.address"),
                    render: function(h, params) {
                        var row = params.row;
                        var lat = Number(row.callat);
                        var lon = Number(row.callon);
                        if (lat && lon) {
                            if (row.address == null) {
                                return h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: function(e) {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            utils.getJiuHuAddressSyn(lon, lat, function(resp) {
                                                if (resp && resp.address) {
                                                    row.address = resp.address;
                                                    LocalCacheMgr.setAddress(lon, lat, resp.address);
                                                }
                                            })
                                        }
                                    }
                                }, lon + "," + lat)

                            } else {
                                return h('span', {}, row.address);
                            }
                        } else {
                            return h('span', {}, vRoot.$t("reportForm.empty"));
                        }
                    },
                },
                {
                    title: vRoot.$t("alarm.action"),
                    width: 175,
                    render: function(h, parmas) {
                        return h(
                            'div', {}, [
                                h(
                                    'Button', {
                                        on: {
                                            click: function(e) {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                vueInstanse.viewMap(parmas);
                                            }
                                        },
                                        props: {
                                            size: 'small',
                                            type: 'info'
                                        }
                                    },
                                    isZh ? '查看地图' : "View map"
                                ),
                                h(
                                    'Button', {
                                        style: {
                                            marginLeft: '5px'
                                        },
                                        on: {
                                            click: function(e) {
                                                vueInstanse.onRowClick(parmas.row);
                                            }
                                        },
                                        props: {
                                            type: "primary",
                                            size: 'small',
                                        }
                                    },
                                    vRoot.$t('reportForm.viewPicture')
                                ),
                            ]
                        );
                    },
                },
            ],
            tableData: [],
            currentIndex: 1,
            trackDetailModal: false,
            deviceName: '',
            cameraImgModal: false,
            cameraImgUrl: '',
        },
        methods: {
            onClickCameraDownload: function() {
                this.cameraImgUrl && window.open(this.cameraImgUrl);
            },
            queryAllAddress: function() {
                var records = this.records;
                records.forEach(function(item) {
                    if (item.address == null) {
                        var uplat = Number(item.callat);
                        var uplon = Number(item.callon);
                        if (uplat && uplon) {
                            utils.getJiuHuAddressSyn(uplon, uplat, function(resp) {
                                if (resp && resp.address) {
                                    item.address = resp.address;
                                    LocalCacheMgr.setAddress(uplon, uplat, resp.address);
                                }
                            })
                        }
                    }
                });

                this.$Message.success(this.$t('monitor.querySucc'));
            },
            exportTableData: function() {
                var data = [
                    [
                        vRoot.$t("reportForm.index"),
                        vRoot.$t("alarm.devName"),
                        vRoot.$t("alarm.devNum"),
                        vRoot.$t("alarm.fileType"),
                        vRoot.$t("monitor.channel"),
                        vRoot.$t("alarm.alarmType"),
                        vRoot.$t("alarm.receivingTime"),
                        vRoot.$t("reportForm.address"),
                    ]
                ];
                this.records.forEach(function(item, index) {
                    var lat = item.callat;
                    var lon = item.callon;
                    var itemArr = [];
                    itemArr.push(index + 1);
                    itemArr.push(item.devicename);
                    itemArr.push(item.deviceid);
                    itemArr.push(item.fileext);
                    itemArr.push(item.channelid);
                    itemArr.push(item.eventcodeStr);
                    itemArr.push(item.endtimeStr);
                    itemArr.push(item.address ? item.address : (lon + ',' + lat));
                    data.push(itemArr);
                });
                var options = {
                    title: vRoot.$t('reportForm.multiMedia'),
                    data: data,
                    dateRange: this.queryDateRange,
                }
                new XlsxCls(options).exportExcel();

            },
            initMap: function() {
                this.markerLayer = null;
                this.mapInstance = utils.initWindowMap('work-details-map');
            },

            cleanSelected: function(treeDataFilter) {
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var item = treeDataFilter[i];
                    if (item != null) {
                        item.checked = false;
                        if (item.children && item.children.length > 0) {
                            that.cleanSelected(item.children);
                        }
                    }
                }
            },
            viewMap: function(row) {
                utils.showWindowMap(this, row)
                this.trackDetailModal = true;
            },
            getFirstMarkerIcon: function(isStart) {
                var iconName = isStart ? 'marker_qidian.png' : 'marker_zhongdian.png';
                var imgPath = '';
                if (utils.isLocalhost()) {
                    imgPath = myUrls.viewhost + 'images/map/' + iconName;
                } else {
                    imgPath = '../images/map/' + iconName;
                };
                if (utils.getMapType() == 'bMap') {
                    return new BMap.Icon("./images/map/" + iconName, new BMap.Size(32, 32), {
                        imageOffset: new BMap.Size(0, 0)
                    });
                } else if (utils.getMapType() == 'gMap') {
                    return imgPath;
                } else {
                    return new ol.style.Style({
                        image: new ol.style.Icon(({
                            crossOrigin: 'anonymous',
                            src: imgPath,
                            rotation: 0, //角度转化为弧度
                            imgSize: [32, 32]
                        }))
                    });
                }
            },
            changePage: function(index) {
                var offset = index * 20;
                var start = (index - 1) * 20;
                this.currentIndex = index;
                this.tableData = this.records.slice(start, offset);
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.lastTableHeight = wHeight - 210;
            },
            onClickQuery: function() {
                var deviceids = [];
                this.checkedDevice.forEach(function(group) {
                    if (!group.children) {
                        if (group.deviceid != null) {
                            deviceids.push(group.deviceid);
                        }
                    }
                });
                if (deviceids.length > 0) {
                    var me = this;
                    var url = myUrls.reportMultiMedias();
                    var data = {
                        startday: this.dateVal[0],
                        endday: this.dateVal[1],
                        offset: timeDifference,
                        deviceids: deviceids
                    }
                    me.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.queryDateRange = data.startday + ' 00:00:00 - ' + data.endday + ' 23:59:59';
                        me.loading = false;
                        if (resp.status === 0) {
                            if (resp.records.length) {
                                var records = [],
                                    index = 1;
                                resp.records.forEach(function(item) {
                                    item.records.forEach(function(item) {
                                        item.index = index;
                                        item.callat = Number(item.callat.toFixed(5));
                                        item.callon = Number(item.callon.toFixed(5));
                                        item.address = LocalCacheMgr.getAddress(item.callon, item.callat);
                                        item.devicename = vstore.state.deviceInfos[item.deviceid] ? vstore.state.deviceInfos[item.deviceid].devicename : item.deviceid;
                                        item.endtimeStr = DateFormat.longToLocalDateTimeStr(item.endtime);
                                        item.eventcodeStr = me.getEventcodeStr(item);
                                        records.push(item);
                                        index++;
                                    })
                                });
                                me.records = records;
                                me.tableData = records.slice(0, 20);
                                me.total = me.records.length;

                            } else {
                                me.tableData = [];
                                me.total = 1;
                                me.records = [];
                            };
                            me.currentIndex = 1;
                        } else {
                            me.tableData = [];
                        }
                    })
                } else {
                    this.$Message.error(this.$t("reportForm.selectDevTip"));
                }
            },
            getEventcodeStr: function(row) {
                var eventcode = row.eventcode;
                var str = '';
                switch (eventcode) {
                    case 0:
                        str = vRoot.$t("alarm.terraceIssued");
                        break;
                    case 1:
                        str = vRoot.$t("alarm.timingAction");
                        break;
                    case 2:
                        str = vRoot.$t("alarm.robberyReport");
                        break;
                    case 3:
                        str = vRoot.$t("alarm.impactRollover");
                        break;
                    default:
                        str = vRoot.$t("alarm.retain");
                }
                return str;
            },
            queryDevicesTree: function() {
                var me = this;
                this.isSpin = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.isSpin = false;
                    me.initZTree(rootuser);
                })
            },
            onRowClick: function(row) {
                this.cameraImgModal = true;
                this.cameraImgUrl = row.url;
            }
        },
        mounted: function() {
            var me = this;
            me.records = [];
            me.initMap();
            this.queryDevicesTree();
            this.calcTableHeight();
            window.onresize = function() {
                me.calcTableHeight();
            }
        }
    })
}



function reportNav(reportNavList) {
    vueInstanse = new Vue({
        el: "#report-nav",
        data: {
            search: isZh ? '搜索' : 'search',
            reportNavList: reportNavList,
            sosoValue: '',
            selectedName: '',
        },
        methods: {
            handleSearch: function() {
                for (var i = 0; i < this.reportNavList.length; i++) {
                    var children = this.reportNavList[i].children
                    for (var j = 0; j < children.length; j++) {
                        var title = children[j].title;
                        if (title.indexOf(this.sosoValue) > -1) {
                            this.selectedName = children[j].name;
                            return;
                        }
                    }
                }
                this.selectedName = "";
            },
            selectdItem: function(name) {
                var vIns = vRoot.$children[3];
                vIns.activeName = name;
                vIns.openedNames = this.getOpenedNames(name);
                vIns.selectditem(name);
                vIns.$nextTick(function() {
                    vIns.$refs.navMenu.updateOpened();
                });
            },
            getOpenedNames: function(sName) {
                var openedNames = [];
                for (var i = 0; i < this.reportNavList.length; i++) {
                    var gName = this.reportNavList[i].name;
                    var children = this.reportNavList[i].children
                    for (var j = 0; j < children.length; j++) {
                        if (children[j].name == sName) {
                            openedNames.push(gName);
                            break;
                        }
                    }
                }
                return openedNames;
            }
        },
        mounted: function() {}
    })
}


// 统计报表
var reportForm = {
    template: document.getElementById('report-template').innerHTML,
    data: function() {
        var me = this;
        return {
            theme: "light",
            isCollapse: false,
            groupslist: [],
            activeName: "reportNav",
            openedNames: [],
            reportNavList: [{
                    title: me.$t("reportForm.menu"),
                    name: 'reportNav',
                    icon: 'ios-stats',
                },
                {
                    title: me.$t("reportForm.drivingReport"),
                    name: 'drivingReport',
                    icon: 'ios-photos',
                    children: [
                        { title: me.$t("reportForm.drivingRecordReport"), name: 'drivingRecordReport', icon: 'ios-speedometer' },
                        { title: me.$t("reportForm.cmdReport"), name: 'cmdReport', icon: 'ios-pricetag-outline' },
                        { title: me.$t("reportForm.posiReport"), name: 'posiReport', icon: 'ios-pin' },
                        { title: me.$t("reportForm.reportmileagesummary"), name: 'groupMileage', icon: 'md-globe' },
                        { title: me.$t("reportForm.mileageMonthReport"), name: 'mileageMonthReport', icon: 'ios-basket-outline' },
                        { title: me.$t("reportForm.reportmileagedetail"), name: 'mileageDetail', icon: 'ios-color-wand' },
                        { title: me.$t("reportForm.parkDetails"), name: 'parkDetails', icon: 'md-analytics' },
                        { title: me.$t("reportForm.acc"), name: 'accDetails', icon: 'md-bulb' },
                        { title: me.$t("reportForm.voiceReport"), name: 'records', icon: 'md-volume-up' },
                        { title: me.$t("reportForm.messageReport"), name: 'messageRecords', icon: 'ios-book' },
                        { title: me.$t("reportForm.rotationStatistics"), name: 'rotateReport', icon: 'ios-aperture' },
                        { title: me.$t("reportForm.ioReport"), name: 'ioReport', icon: 'md-contrast' },
                        { title: me.$t('reportForm.tripReport'), name: 'tripReport', icon: 'md-repeat' },
                        { title: me.$t('reportForm.workingHoursReport'), name: 'workingHours', icon: 'ios-construct-outline' },
                        { title: me.$t("reportForm.idleReport"), name: 'idleReport', icon: 'md-speedometer' },
                    ]
                },
                {
                    title: me.$t("reportForm.warningReport"),
                    name: 'warningReport',
                    icon: 'logo-wordpress',
                    children: [
                        { title: me.$t("reportForm.allAlarm"), name: 'allAlarm', icon: 'md-warning' },
                        { title: me.$t("reportForm.phoneAlarm"), name: 'phoneAlarm', icon: 'ios-call' },
                        { title: me.$t("reportForm.wechatAlarm"), name: 'wechatAlarm', icon: 'md-ionitron' },
                        { title: me.$t("reportForm.rechargeRecords"), name: 'rechargeRecords', icon: 'ios-list-box-outline' },
                        { title: me.$t("reportForm.speedingReport"), name: 'speedingReport', icon: 'md-remove-circle' },
                        { title: me.$t('reportForm.multiMedia'), name: 'multiMedia', icon: 'ios-ionitron-outline' },
                        { title: me.$t('reportForm.deviceMsg'), name: 'deviceMsg', icon: 'ios-notifications-outline' },
                        { title: me.$t('reportForm.pushTextReport'), name: 'pushTextReport', icon: 'ios-paper-outline' },
                        { title: me.$t('reportForm.checkReport'), name: 'checkReport', icon: 'ios-create-outline' },
                        { title: me.$t('reportForm.fenceReport'), name: 'fenceReport', icon: 'ios-flag-outline' },
                    ]
                },
                {
                    title: me.$t("reportForm.onlineStatistics"),
                    name: 'operateReport',
                    icon: 'md-stats',
                    children: [
                        { title: me.$t("reportForm.comprehensiveStatistics"), name: 'reportOnlineSummary', icon: 'md-sunny' },
                        { title: me.$t("reportForm.offlineReport"), name: 'dropLineReport', icon: 'ios-git-pull-request' },
                        { title: me.$t("reportForm.dailyVehicleOnlineRate"), name: 'deviceOnlineDaily', icon: 'md-bulb' },
                        { title: me.$t("reportForm.dailyFleetOnlineRate"), name: 'groupsOnlineDaily', icon: 'md-contacts' },
                        { title: me.$t("reportForm.monthlyVehicleOnlineRate"), name: 'deviceMonthOnlineDaily', icon: 'md-contrast' },
                        { title: me.$t("reportForm.newAddedDeviceReport"), name: 'newEquipmentReport', icon: 'md-add' },
                        { title: me.$t("reportForm.deviceTypeDistribution"), name: 'deviceTypeDistribution', icon: 'ios-git-merge' },
                        { title: me.$t("reportForm.onlineStatisticsDay"), name: 'onlineStatisticsDay', icon: 'ios-trending-up' },
                    ]
                },
                {
                    title: me.$t("reportForm.oilReport"),
                    name: 'oilConsumption',
                    icon: 'ios-speedometer-outline',
                    children: [
                        { title: me.$t("reportForm.oilMonthReport"), name: 'oilMonthReport', icon: 'ios-grid' },
                        { title: me.$t("reportForm.oilMonthDetail"), name: 'oilMonthDetail', icon: 'md-grid' },
                        { title: me.$t("reportForm.oilDayDetail"), name: 'oilDayDetail', icon: 'ios-grid-outline' },
                        { title: me.$t("reportForm.dayOilConsumption"), name: 'dayOil', icon: 'ios-stopwatch-outline' },
                        { title: me.$t("reportForm.oilworkingHoursReport"), name: 'oilworkingHours', icon: 'ios-appstore-outline' },
                        { title: me.$t("reportForm.idleOilReport"), name: 'idleOilReport', icon: 'md-speedometer' },
                        { title: me.$t("reportForm.dateOilConsumption"), name: 'timeOilConsumption', icon: 'ios-timer-outline' },
                        { title: me.$t("reportForm.mileageOilConsumption"), name: 'mileageOilConsumption', icon: 'ios-timer-outline' },
                        { title: me.$t("reportForm.addLeakMonthDetail"), name: 'addLeakMonthDetail', icon: 'ios-analytics-outline' },
                        { title: me.$t("reportForm.addOil"), name: 'refuelingReport', icon: 'ios-trending-up' },
                        { title: me.$t("reportForm.reduceOil"), name: 'oilLeakageReport', icon: 'ios-trending-down' },
                        { title: me.$t("reportForm.fuelConsumptionTrend"), name: 'fuelConsumptionTrend', icon: 'ios-pulse-outline' },

                        // { title: me.$t("reportForm.fuelRate"), name: 'powerWaste', icon: 'ios-pulse-outline' },  
                    ]
                },
                {
                    title: me.$t("reportForm.weightReport"),
                    name: 'weightReport',
                    icon: 'md-keypad',
                    children: [
                        { title: me.$t("reportForm.timeWeightConsumption"), name: 'timeWeightConsumption', icon: 'ios-timer-outline' },
                        { title: me.$t("reportForm.weightSummary"), name: 'weightSummary', icon: 'ios-bus-outline' },
                    ]
                },
                {
                    title: me.$t("reportForm.tempReport"),
                    name: 'temperatureConsumption',
                    icon: 'ios-color-wand-outline',
                    children: [
                        { title: me.$t("reportForm.temperatureChart"), name: 'temperature', icon: 'ios-stopwatch-outline' },
                    ]
                },
                {
                    title: me.$t("reportForm.logisticsReport"),
                    name: 'logisticsReport',
                    icon: 'ios-bicycle',
                    children: [
                        { title: me.$t("reportForm.driverWorkDetails"), name: 'driverWorkDetails', icon: 'md-car' },
                    ]
                },
                {
                    title: me.$t("reportForm.insurMgr"),
                    name: 'insure',
                    icon: 'md-medkit',
                    children: [
                        { title: me.$t("reportForm.insurRecord"), name: 'insureRecords', icon: 'ios-list-box-outline' },
                        { title: me.$t("reportForm.salesRecord"), name: 'salesRecord', icon: 'ios-book-outline' },
                    ]
                },
            ]
        }
    },
    methods: {
        selectditem: function(name) {
            var pageName = name.toLowerCase() + ".html";
            this.loadPage(pageName);
        },
        handleClickDropdown: function(name) {
            this.activeName = name;
            this.selectditem(name);
        },
        loadPage: function(page) {
            vueInstanse && vueInstanse.$destroy && vueInstanse.$destroy();
            var me = this;
            var pagePath = null;
            if (utils.isLocalhost()) {
                pagePath = myUrls.viewhost + 'view/reportform/' + page
            } else {
                pagePath = '../view/reportform/' + page
            }
            this.$Loading.start();
            $('#report-right-wrap').load(pagePath, function() {
                me.$Loading.finish();
                var groupslist = deepClone(me.groupslist);
                window.onresize = null;
                switch (page) {
                    case 'reportnav.html':
                        var reportNavList = deepClone(me.reportNavList);
                        reportNavList.shift();
                        reportNav(reportNavList);
                        break;
                    case 'rechargerecords.html':
                        rechargeRecords(groupslist);
                        break;
                    case 'cmdreport.html':
                        cmdReport(groupslist);
                        break;
                    case 'allalarm.html':
                        allAlarm(groupslist);
                        break;
                    case 'posireport.html':
                        posiReport(groupslist);
                        break;
                    case 'mileagedetail.html':
                        reportMileageDetail(groupslist);
                        break;
                    case 'mileagemonthreport.html':
                        mileageMonthReport(groupslist);
                        break;
                    case 'groupmileage.html':
                        groupMileage(groupslist);
                        break;
                    case 'parkdetails.html':
                        parkDetails(groupslist);
                        break;
                    case 'accdetails.html':
                        accDetails(groupslist);
                        break;
                    case 'rotatereport.html':
                        rotateReport(groupslist);
                        break;
                    case 'speedingreport.html':
                        speedingReport(groupslist);
                        break;
                    case 'multimedia.html':
                        multiMedia(groupslist);
                        break;
                    case 'records.html':
                        devRecords(groupslist);
                        break;
                    case 'messagerecords.html':
                        messageRecords(groupslist);
                        break;
                    case 'phonealarm.html':
                        phoneAlarm(groupslist);
                        break;
                    case 'insurerecords.html':
                        insureRecords(groupslist);
                        break;
                    case 'salesrecord.html':
                        salesRecord(groupslist);
                        break;
                    case 'wechatalarm.html':
                        wechatAlarm(groupslist);
                        break;
                    case 'reportonlinesummary.html':
                        reportOnlineSummary(groupslist);
                        break;
                    case 'droplinereport.html':
                        dropLineReport(groupslist);
                        break;
                    case 'deviceonlinedaily.html':
                        deviceOnlineDaily(groupslist);
                        break;
                    case 'groupsonlinedaily.html':
                        groupsOnlineDaily(groupslist);
                        break;
                    case 'devicemonthonlinedaily.html':
                        deviceMonthOnlineDaily(groupslist);
                        break;
                    case 'newequipmentreport.html':
                        newEquipmentReport();
                        break;
                    case 'devicetypedistribution.html':
                        deviceTypeDistribution(groupslist);
                        break;
                    case 'onlinestatisticsday.html':
                        onlineStatisticsDay(groupslist);
                        break;
                    case 'timeoilconsumption.html':
                        timeOilConsumption(groupslist);
                        break;
                    case 'mileageoilconsumption.html':
                        mileageOilConsumption(groupslist);
                        break;
                    case 'timeweightconsumption.html':
                        timeWeightConsumption(groupslist);
                        break;
                    case 'weightsummary.html':
                        weightSummary(groupslist);
                        break;
                    case 'dayoil.html':
                        dayOil(groupslist);
                        break;
                    case 'oilmonthreport.html':
                        oilMonthReport(groupslist);
                        break;
                    case 'oilmonthdetail.html':
                        oilMonthDetail(groupslist);
                        break;
                    case 'oildaydetail.html':
                        oilDayDetail(groupslist);
                        break;
                    case 'refuelingreport.html':
                        refuelingReport(groupslist);
                        break;
                    case 'oilleakagereport.html':
                        oilLeakageReport(groupslist);
                        break;
                    case 'fuelconsumptiontrend.html':
                        fuelConsumptionTrend(groupslist);
                        break;
                    case 'addleakmonthdetail.html':
                        addLeakMonthDetail(groupslist);
                        break;
                    case 'powerwaste.html':
                        powerWaste(groupslist);
                        break;
                    case 'oilworkinghours.html':
                        oilWorkingHours(groupslist);
                        break;
                    case 'idleoilreport.html':
                        idleOilReport(groupslist);
                        break;
                    case 'idlereport.html':
                        idleReport(groupslist);
                        break;
                    case 'temperature.html':
                        temperature(groupslist);
                        break;
                    case 'driverworkdetails.html':
                        driverWorkDetails(groupslist);
                        break;
                    case 'ioreport.html':
                        ioReport(groupslist);
                        break;
                    case 'devicemsg.html':
                        deviceMsg(groupslist);
                        break;
                    case 'pushtextreport.html':
                        pushTextReport(groupslist);
                        break;
                    case 'checkreport.html':
                        checkReport(groupslist);
                        break;
                    case 'fencereport.html':
                        fenceReport(groupslist);
                        break;
                    case 'tripreport.html':
                        tripReport(groupslist);
                        break;
                    case 'workinghours.html':
                        workingHoursReport(groupslist);
                        break;
                    case 'drivingrecordreport.html':
                        drivingRecordReport(groupslist);
                        break;
                }
            });
        },
        getMonitorListByUser: function(callback) {
            var me = this;
            var url = myUrls.monitorListByUser();
            utils.sendAjax(url, { username: userName }, function(resp) {
                if (resp.status == 0) {
                    if (resp.groups && resp.groups.length) {
                        callback(resp.groups);
                    } else {
                        callback([]);
                    }
                } else if (resp.status == 3) {
                    me.$Message.error(me.$t("monitor.reLogin"));
                    localStorage.setItem('token', "");
                    setTimeout(function() {
                        window.location.href = 'index.html';
                    }, 2000);
                } else {
                    if (resp.cause) {
                        me.$Message.error(resp.cause)
                    }
                }
            })
        },
        toAlarmRecords: function(activeName, pageHtml) {
            var me = this;
            this.activeName = activeName;
            this.openedNames = ['warningReport'];
            this.$nextTick(function() {
                me.$refs.navMenu.updateOpened();
                me.loadPage(pageHtml);
            })
        },
        getDeviceTypeName: function(deviceTypeId) {
            var typeName = "",
                deviceTypes = this.deviceTypes;
            for (var index = 0; index < deviceTypes.length; index++) {
                var element = deviceTypes[index];
                if (element && element.devicetypeid === deviceTypeId) {
                    typeName = element.typename;
                    break
                }
            }
            return typeName;
        },
    },
    computed: {
        deviceTypes: function() {
            return this.$store.state.deviceTypes;
        },
    },
    watch: {
        isCollapse: function() {

            setTimeout(function() {
                vueInstanse.myChart && vueInstanse.myChart.resize();
                vueInstanse.chartsIns && vueInstanse.chartsIns.resize();
                vueInstanse.chartsIns1 && vueInstanse.chartsIns1.resize();
            }, 300)
        }
    },
    mounted: function() {
        var me = this;
        me.groupslist = globalGroups;
        if (isToAlarmListRecords) {
            me.toAlarmRecords("allAlarm", "allalarm.html");
        } else if (isToPhoneAlarmRecords) {
            me.toAlarmRecords("phoneAlarm", "phonealarm.html");
        } else {
            me.selectditem('reportNav');
        }
    }
}